Testing the type of a DOM element in JavaScript

前端 未结 7 1051
孤街浪徒
孤街浪徒 2020-12-13 16:46

Is there a way to test the type of an element in JavaScript?

The answer may or may not require the prototype library, however the following setup does make use of t

7条回答
  •  北海茫月
    2020-12-13 17:25

    Although the previous answers work perfectly, I will just add another way where the elements can also be classified using the interface they have implemented.

    Refer W3 Org for available interfaces

    console.log(document.querySelector("#anchorelem") instanceof HTMLAnchorElement);
    console.log(document.querySelector("#divelem") instanceof HTMLDivElement);
    console.log(document.querySelector("#buttonelem") instanceof HTMLButtonElement);
    console.log(document.querySelector("#inputelem") instanceof HTMLInputElement);
    Anchor element
    
    Div Element

    The interface check can be made in 2 ways as elem instanceof HTMLAnchorElement or elem.constructor.name == "HTMLAnchorElement", both returns true

提交回复
热议问题