简体   繁体   中英

Test if object is a DOM element

A JavaScript function receives one argument that may be a DOM element or not. How ensure that argument is a DOM element and not another object?

With modern browsers I think it is something like

e instanceof Element
e instanceof Text // text node

Try this.

To check if it is a DOM object.

if(arg.tagName){ 
   //Its a dom element
}

To check if it is a jQuery object

if(arg.jquery){
   //Its a jQuery object
}

Working demo

Alternatively you can try this function which will return true if the element passed as an argument is a DOM element.

function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement :
    typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
);

el instanceof Node will give you true if el is a part of DOM. el instanceof Element - true if it is also an Element.

just check the object that is it have a innerHTML function or not.

For example :

function (obj ) {
    if(!!obj.innerHTML) // force the function to be boolean 
    {
         // do something here if it was a html element 
    }
    else {
         // do stuff here if it wasn't
    }



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM