How can I determine the type of an HTML element in JavaScript?

后端 未结 4 1307
时光说笑
时光说笑 2020-11-30 20:21

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

, a
f
4条回答
  •  眼角桃花
    2020-11-30 20:39

    nodeName is the attribute you are looking for. For example:

    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

    element you could do it as follows:

    elt.nodeName == "DIV"
    

    While this would not give you the expected results:

    elt.nodeName == "
    "

提交回复
热议问题