1

I have been going through some code and converting all the jQuery to vanilla JS. Below is some code I converted successfully (commented out is the jQuery). I was having some trouble appending it to the head until I added [0] at the end.I know square brackets are used when accessing an array, but I'm not exactly sure why they were needed in this instance. Could someone explain?

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'
    //  });
KatherineMichelle
  • 453
  • 10
  • 27
  • 1
    `document.getElementsByTagName` returns multiple elements. Here you are using first element – Gaur93 Dec 08 '17 at 06:16

1 Answers1

1

getElementsByTagName always returns an array-like HTMLCollection of elements, so you need to take the first element to access your <head> element.

klugjo
  • 19,422
  • 8
  • 57
  • 75
  • 1
    Of course. Thank you. Sorry I'm very new to this, of course I could have figured that out by just researching but I was focusing my research on use of square brackets. Thanks for your help! – KatherineMichelle Dec 08 '17 at 06:17
  • 1
    @brk updated my answer to reflect the fact that it is not an array but an HTMLCollection – klugjo Dec 08 '17 at 06:25