3

Html:

<div class="project-box">
 <img src="img/ifix.jpg" class="thumbnail img-responsive">
   <div class="hover-box">
     <h2>TITLE</h2>
     <p>Description of title</p>
   </div>
 </div>

javascipt:

window.onload = function(){

var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
  alert(img.clientWidth); 
};

I'm trying to get the img width and eventually the img height using pure JavaScript I know this is a lot easier with jQuery but I want to do it using only JavaScript. EDIT: I realized I was not specifying the array for the img and project

working js:

window.onload = function(){

var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
 alert(img[0].offsetWidth);
};
1
  • Try img.clientWidth. Commented Nov 13, 2013 at 3:03

4 Answers 4

3

Both getElementsByClassName and getElementsByTagName returns an array of objects, so you need to access the actual element by its index then call its methods/properties

window.onload = function () {
    var project = document.getElementsByClassName('project-box')[0];
    var img = project.getElementsByTagName('img')[0];
    alert(img.clientWidth);
};

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

thank you I relized this right before reading your answer so I did it a bit different but still works I gave you the check since its still the correct solution
1

I believe project.getElementsByTagName('img'); is returning an array, even if it only has one object.

Try something like

window.onload = function(){

var project = document.getElementsByClassName('project-box');
img = project.getElementsByTagName('img');
  alert(img.pop().width); //This should remove the element from the array and then call width
};

2 Comments

there are several of the project-box and img i tried adding img[0].width but still no result
Oh! I just realized you aren't declaring the variable img.
0

Try this one:

alert(img.clientWidth);

1 Comment

Sorry, i realized that img is an array of elements, it must be img[0].clientWidth
0

The reason this is not working is because .getElementsByClassName() and .getElementsByTagName() both wrap elements inside an [object HTMLContainer], you need to select the first element from each of these objects.

This code should work:

window.onload = function()
{
    var project = document.getElementsByClassName('project-box');
            img = project[0].getElementsByTagName('img');

    console.log(img[0].clientWidth);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.