getElementsByTagName 中的零索引是什么?



有人能说出,使用这个零索引时会发生什么?

document.getElementsByTagName('head')[0].appendChild(script);

函数getElementsByTagName()将返回一个类似数组的 HTMLCollection 对象,当您访问索引为零的对象时,它将为您提供该数据结构的第一个条目。

在 JavaScript 中,索引从零开始(与许多编程语言一样(。

getElementsByTagName返回具有给定标签名称的元素的实时 HTML 查询。HTMLCollection接口表示类似数组的元素对象。

因此,传递零将给出第一个index中的元素,即第 0 个索引

var elements = document.getElementsByTagName('div');
console.log(elements);
console.log(elements[0]) // <div> First </div>
<div> First </div>
<div> Second </div>
<div> Third </div>
<div> Fourth </div>

var js = document.createElement('script');
js.src = 'myscript.js';
document.getElementsByTagName('head')[0].appendChild(js);

你得到所有的头元素(应该只有一个(,然后在那里添加脚本,所以结果是

<html>
<head>
<script>
...

如果文档中没有 HEAD,则大多数浏览器将创建 head 元素,即使标签不存在也是如此。

看看这个,它可能会有所帮助。 http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/

最新更新