Why is element.tagName undefined?
I was having a little play a开发者_如何学运维round this morning and I thought it would be fun to do something silly and try and write all the tagnames of a page on that page using something like this
var elements = document.getElementsByTagName("*");
for(var element in elements) {
document.write(element.tagName + "<br />");
}
However all that gets written is undefined. Why is this? Oh and I'm using Firefox.
for...in
is not guaranteed to work for a NodeList
(which is what document.getElementsByTagName()
returns), and even when it does, what you'll be getting as the value of element
will be not be a reference to the element but rather a property name, such as the numeric index of the element in the NodeList
. Use a normal for
loop instead.
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; ++i) {
document.write(elements[i].tagName + "<br />");
}
Also, document.write()
won't work as you might expect after the document has loaded, which is when you'd typically use document.getElementsByTagName()
. A better mechanism would be to populate an element in the page:
<div id="debug"></div>
Script:
var elements = document.getElementsByTagName("*");
var debugDiv = document.getElementById("debug");
var tagNames = [];
for (var i = 0; i < elements.length; ++i) {
tagNames.push(elements[i].tagName);
}
debugDiv.innerHTML = tagNames.join("<br>");
Because you're using a for...in
loop, element
is actually the item's key and not the value. elements[element]
would give you the correct result, but you should use a proper for
loop instead:
for (var i = 0; i < elements.length; i++) {
document.write(elements[i].tagName + "<br />");
}
This is because for...in
may iterate over other enumerable properties that are not elements of the collection. These properties can differ between browsers.
You could try:
var elements = document.getElementsByTagName("*");
for (int i = 0; i < elements.length; i++)
{
document.write(elements.item(i).tagName + "<br />");
}
I suppose that is impossible, and is possible with jQuery/Sizzle HTML/CSS Selector:
$('*');
With that function/method you can only select "all available HTML tags" in your current document.
For example:
document.getElementByTagName('html');
document.getElementByTagName('head');
document.getElementByTagName('body');
document.getElementByTagName('h3');
document.getElementByTagName('p');
document.getElementByTagName('pre');
document.getElementByTagName('code');
document.getElementByTagName('metaforce'); // being a custom HTML(5) tag
精彩评论