Search code examples
javascripthtmlelements

How to test if given variable contains a valid html element?


That is such with tag name and attributes so then I can safely use for example hasAttribute, tagName and other similar methods.

(My question is for a method of positively asking for html element, not for example ruling out all possibilities like string, number, some kind of other object etc.)


Solution

  • You check if it is an instance of HTMLElement

    if (varName instanceof HTMLElement){
       // do what you want with the node
    }