问题
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