Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
139
rated 0 times [  145] [ 6]  / answers: 1 / hits: 27013  / 13 Years ago, thu, april 28, 2011, 12:00:00

Here is my html



<a href=index.php><img id=testimg   src=images/logo.png/></a>


Here is my javascript



function getW(){
var theImg = document.getElementById('testimg');
return theImg;
}

theImg = getW();

if (theImg.width > 119){
document.write(theImg.width);
}


Now when I use this script it out puts the img width



However when I use this script



function getW(){
var theImg = document.getElementsByTagName(img);
return theImg;
}

theImg = getW();

if (theImg.width > 119){
document.write(theImg.width);
}


It doesn't output anything. What is the difference and why would this 2nd script work?



Thanks!


More From » javascript

 Answers
43

Because getElementsByTagName() returns a set of multiple elements (note the elements). You'd need to use [0] to get the first matched.



On the other hand, an id should always be unique so getElementById() returns a reference to a single element.


[#92515] Wednesday, April 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gonzalo

Total Points: 336
Total Questions: 114
Total Answers: 98

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;