document.getElementsByTagName("img"); 与 document.getElementById('testimg'); 比较

Chr*_*ris 2 javascript

这是我的html

<a href="index.php"><img id="testimg"   src="images/logo.png"/></a>
Run Code Online (Sandbox Code Playgroud)

这是我的 JavaScript

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

theImg = getW();

if (theImg.width > 119){
    document.write(theImg.width);
}
Run Code Online (Sandbox Code Playgroud)

现在,当我使用这个脚本时,它会输出 img 宽度

但是当我使用这个脚本时

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

theImg = getW();

if (theImg.width > 119){
    document.write(theImg.width);
}
Run Code Online (Sandbox Code Playgroud)

它不输出任何内容。有什么区别以及为什么第二个脚本会起作用?

谢谢!

ale*_*lex 5

因为getElementsByTagName()返回一组多个元素(注意elements)。您需要使用[0]来获得第一个匹配。

另一方面, anid应该始终是唯一的,因此getElementById()返回对单个元素的引用。