如何确定JavaScript中HTML元素的类型? [英] How can I determine the type of an HTML element in JavaScript?
本文介绍了如何确定JavaScript中HTML元素的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种方法来确定JavaScript中HTML元素的类型。它有id,但元素本身可以是一个div,一个表单域,一个fieldset等等。我如何实现这个?
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?
推荐答案
nodeName
是您要查找的属性。例如:
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
请注意, nodeName
返回大写的元素名称而没有尖括号,这意味着如果你想检查一个元素是否是一个< div>
元素,你可以这样做:
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:
elt.nodeName == "DIV"
虽然这不会给您预期的结果:
While this would not give you the expected results:
elt.nodeName == "<div>"
这篇关于如何确定JavaScript中HTML元素的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文