Search code examples
javascriptgetelementsbytagname

What is the zero index in getElementsByTagName?


Could someone tell, what happens when using this zero index?

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

Solution

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

    You get all head elements (there should be only one) and you add the script there so the result is

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

    if there's no head in the document, most browsers will create the head element even if the tag is not there.

    Have a look at this, it might can help. http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/