开发者

Test if object is a DOM element

开发者 https://www.devze.com 2023-04-01 05:46 出处:网络
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 somethi

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
    }



}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号