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

后端 未结 4 1299
时光说笑
时光说笑 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:28

    You can use generic code inspection via instanceof:

    var e = document.getElementById('#my-element');
    if (e instanceof HTMLInputElement) {}         // <input>
    elseif (e instanceof HTMLSelectElement) {}    // <select>
    elseif (e instanceof HTMLTextAreaElement) {}  // <textarea>
    elseif (  ... ) {}                            // any interface
    

    Look here for a complete list of interfaces.

    0 讨论(0)
  • 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 <div> element you could do it as follows:

    elt.nodeName == "DIV"
    

    While this would not give you the expected results:

    elt.nodeName == "<div>"
    
    0 讨论(0)
  • 2020-11-30 20:48

    Sometimes you want element.constructor.name

    document.createElement('div').constructor.name
    // HTMLDivElement
    
    document.createElement('a').constructor.name
    // HTMLAnchorElement
    
    document.createElement('foo').constructor.name
    // HTMLUnknownElement
    
    0 讨论(0)
  • 2020-11-30 20:49

    What about element.tagName?

    See also tagName docs on MDN.

    0 讨论(0)
提交回复
热议问题