document.getElementById()的返回类型是什么

时间:2017-06-19 14:46:14

标签: javascript

此代码段中变量“element”的类型是什么? 我认为这是一个数字(ID或其他),但现在,我不知道。 代码有效,但我不明白,为什么var元素可以在for循环中使用,比如数组。对此有任何解释吗?

   <script type="text/javascript">
            function showAtrributes() {
                var element = document.getElementById("videos");
                var listAttributes = "";
                for(var attribute in element) {
                    var valueOfAtrrib = element.getAttribute(attribute);
                    listAttributes = listAttributes + attribute + ": " + valueOfAttrib + "\n";
                }
                alert(listAttributes);
            }
        </script>

5 个答案:

答案 0 :(得分:1)

  

getElementById()方法返回具有ID的元素   具有指定值的属性。   [....]   如果不存在具有指定ID的元素,则返回null。

因此它返回一个HTMLElement对象

source

答案 1 :(得分:1)

  

document.getElementById()

的返回类型是什么

Element。它返回对DOM中元素的实际对象的引用(如果找不到null,则返回id)。详细说明:

  

我认为这是一个数字(ID或其他)

不,那是"video"(您用来查找它的字符串)。它也可以从Element对象的id属性访问。

  

代码有效,但我不明白为什么var元素可以在for循环中使用,比如数组。

for-in主要不在数组上使用,而是用于对象。它在数组上工作的唯一原因是数组是对象。 (有关详细信息,请参阅this question's answersthis page on MDN。)DOM元素是对象,因此您可以通过for-in循环遍历其可枚举属性。

答案 2 :(得分:0)

document.getElementById()的返回类型是Element Object或 null 。请参阅MDN中的以下链接:

答案 3 :(得分:0)

看起来你真的质疑为什么for循环工作,而不是getElementById返回什么样的对象。阅读这篇文章:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

for(var in ....)语法导致Javascript迭代由....指定的对象的属性。

答案 4 :(得分:0)

返回类型可以是程序员为JS VM库定义的任何类型。例如,使用SpiderMonkey的webcwebbrowser返回HTMLElement JSClass的JSObject,它通过在基础内部HTMLElement对象上调用CreateJSClass来获取。

相关问题