方括号[]的用户在JavaScript中附加到head的链接时

时间:2017-12-08 06:14:53

标签: javascript jquery arrays object

我一直在浏览一些代码并将所有jQuery转换为vanilla JS。下面是我成功转换的一些代码(注释掉是jQuery)。在我最后添加[0]之前,我遇到了一些麻烦。我知道在访问数组时会使用方括号,但我不确定为什么在这个实例中需要它们。有人可以解释一下吗?

var head = document.getElementsByTagName('head')[0];
    var linkScript = document.createElement('link');
    linkScript.type = 'text/css';
    linkScript.rel = 'stylesheet';
    linkScript.href = purecommHostFiles + 'style.css';
    head.appendChild(linkScript);

    // $('<link>')
    //  .appendTo('head')
    //  .attr({
    //      type: 'text/css',
    //      rel: 'stylesheet',
    //      href: purecommHostFiles + 'style.css'
    //  });

1 个答案:

答案 0 :(得分:1)

getElementsByTagName始终返回类似数组HTMLCollection的元素,因此您需要使用第一个元素来访问<head>元素。