Jamna
Jamna

Reputation: 2577

Getting a single element with `getElementsByTagName`

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?

Upvotes: 1

Views: 19196

Answers (3)

Molecular Man
Molecular Man

Reputation: 22386

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

Upvotes: 9

Quentin
Quentin

Reputation: 943216

getElementsByTagName returns a NodeList. It might have no items in it. It might have one. It might have many. You can see how many are in it by testing its .length.

It would be confusing if it sometimes returned a NodeList and sometimes returned an ElementNode.

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816334

getElementsByTagName [docs] always returns a NodeList. It does not matter whether an element with a certain tag exists only once.

It would be bad if the function behaved inconsistently.

Upvotes: 3

Related Questions