Reputation: 225
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);
};
Upvotes: 3
Views: 10677
Reputation: 3608
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);
};
Upvotes: 0
Reputation: 388446
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
Upvotes: 3
Reputation: 13
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
};
Upvotes: 1