开发者

document.getElementsByTagName("img"); vs. document.getElementById('testimg');

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 the开发者_StackOverflowImg;
}

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!


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.


gEBTN returns a node list. Do theImg[0] for the first element.

For your other question, do a for loop on the length of the nodeList.


getElementsByTagName() returns an array of nodes (elements) that match the tag name you provided. So while your first code example returns a single element, your second one is working with an array.

In order to get the image you are looking for through getElementsByTagName, you will need to either need to do an attribute search (finding an appropriate name or id tag, for example) or simply know the order of it on the page.

In your example, theImg[0] will return the image you are looking for.


Replace on your code:

var theImg = document.getElementsByTagName("img");

with this code:

var theImg = document.getElementsByTagName("img").item(0);

or with this code:

var theImg = document.getElementsByTagName("img")[0];

Both are equivalent, pay attention to the .item(0), it is equivalent to [0].

The zero is correct if the desired image is the first, else replace the zero to a correct index.


The method document.getElementById('testimg') returns a real element object whose id is testimg. the method document.getElementsByTagName("img") will return an array including all element objects whose tag is img.

But if there are more than one element whose id is testimg, the method document.getElementById('testimg') will return the first one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜