getElementsByTagName (“div”).length returns zero for any webpage

别等时光非礼了梦想. 提交于 2019-12-22 10:29:29

问题


I am trying to develop a Firefox extension. The following code:

var divList = document.getElementsByTagName("div") ;
Components.utils.reportError("num of divs = " + divList.length) ;

Always says:- num of divs = 0.

I don't understand what is the mistake that I am making in this simple piece of code. When I replace "div" with "*", I always get a value around 1100 on any webpage.


回答1:


Not sure what is the difference in the extension context, but it might have to do with namespaces - https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName. What is the tag of the first of 1100 elements you get when using "*"?




回答2:


May be the code is run when the DOM is not ready.

Try to put the JS code inside a script tag at the very end of the body tag.
I'm not sure why * gets so many items though.



来源:https://stackoverflow.com/questions/4179209/getelementsbytagname-div-length-returns-zero-for-any-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!