getElementsByTagNameでhtml,head,bodyを取得しないほうが良い

html,head,bodyは短いコードで取得可能

JavaScriptのコードを見ていると、いまだにhtml,head,bodyを取得するのにgetElementsByTagNameを使用しているコードを見かけることがある。

getElementsByTagNameは指定されたタグ名を持つ要素のHTMLCollectionを返すメソッドで、通常この3つはHTML内に1つしかないため、これに[0]を付けることで要素の取得ができる。

document.getElementsByTagName('html')[0]
document.getElementsByTagName('head')[0]
document.getElementsByTagName('body')[0]

だが、html,head,bodyのHTMLタグに関してはgetElementsByTagNameを使用しなくても、以下の短い書き方で要素の取得ができるので、こちらを使用したほうが良いだろう。

document.documentElement // get html tag element
document.head
document.body

html,head,bodyの要素を短いコードで取得したサンプル