document.head v. document.getElementsByTagName(“head”)[0]

后端 未结 4 2103
遇见更好的自我
遇见更好的自我 2021-02-02 14:56

What is the difference between using document.head and using document.getElementsByTagName(\"head\")[0]? Tests I ran showed that they both take about a

4条回答
  •  旧巷少年郎
    2021-02-02 15:43

    Just convenience because you are only supposed to have one per page. Just like there is a direct shortcut to document.body, although document.body is standard and you wouldn't need the fallback.

    document.body || document.getElementsByTagName("body")[0]
    

    I wouldn't use document.head unless you only support IE9+. Until then, I would stick to document.getElementsByTagName("head")[0]

    If you want a version that you don't have to change as time goes by, you can do the following at the top of your script

    document.head = document.head || document.getElementsByTagName("head")[0];
    

    That way you can just change that one place when you drop support for IE8 (or may even leave it there since it doesn't hurt, but it will be dead code). The above code would also make sure you only query the DOM once

提交回复
热议问题