I need a way to determine the type of an HTML element in JavaScript. It has the id, but the element itself could be a div, a form field, a fieldset, etc. How can I achieve this?
我需要一种方法来确定JavaScript中HTML元素的类型。它有id,但元素本身可以是div,表单字段,字段集等。我怎样才能实现这个目标?
2 个解决方案
#1
192
nodeName
is the attribute you are looking for. For example:
nodeName是您要查找的属性。例如:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
请注意,nodeName返回大写的元素名称而没有尖括号,这意味着如果要检查元素是否为
elt.nodeName == "DIV"
While this would not give you the expected results:
虽然这不会给你预期的结果:
elt.nodeName == "<div>"
#2
29
What about element.tagName
?
element.tagName怎么样?
See also tagName
docs on MDN.
另请参阅MDN上的tagName文档。
#1
192
nodeName
is the attribute you are looking for. For example:
nodeName是您要查找的属性。例如:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
请注意,nodeName返回大写的元素名称而没有尖括号,这意味着如果要检查元素是否为
elt.nodeName == "DIV"
While this would not give you the expected results:
虽然这不会给你预期的结果:
elt.nodeName == "<div>"
#2
29
What about element.tagName
?
element.tagName怎么样?
See also tagName
docs on MDN.
另请参阅MDN上的tagName文档。