开发者

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.getEleme开发者_JAVA百科ntsByTagName("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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜