Getting a single element with `getElementsByTagName`

Jamna picture Jamna · Jul 21, 2011 · Viewed 17.7k times · Source

I know that if we want to find a group of elements, getElementsByTagName is the method for us and it returns a NodeList. but if we are looking for tag name with "body" , then why we need to add [0] after the ("body") element? There is only one body tag in an HTML document.

 var body = document.getElementsByTagName("body")[0];
 body.className = "unreadable";

why we cant write this code without index[0] like this

 var body = document.getElementsByTagName("body");
 body.className = "unreadable";

If i write this code the class unreadable will not be added with body tag ...why?

Answer

Molecular Man picture Molecular Man · Jul 21, 2011

Because document.getElementsByTagName allways returns NodeList. If you want find easier way to retrieve body you can use just document.body