JavaScript isDOM — How do you check if a JavaScrip

2018-12-31 20:11发布

I'm trying to get:

document.createElement('div')  //=> true
{tagName: 'foobar something'}  //=> false

In my own scripts, I used to just use this since I never needed tagName as a property:

if (!object.tagName) throw ...;

So for the second object, I came up with the following as a quick solution -- which mostly works. ;)

The problem is, it depends on browsers enforcing read-only properties, which not all do.

function isDOM(obj) {
  var tag = obj.tagName;
  try {
    obj.tagName = '';  // Read-only for DOM, should throw exception
    obj.tagName = tag; // Restore for normal objects
    return false;
  } catch (e) {
    return true;
  }
}

Is there a good substitute?

30条回答
高级女魔头
2楼-- · 2018-12-31 20:13

here's a trick using jQuery

var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")

$(obj).html() == undefined // true
$(element).html() == undefined // false

so putting it in a function:

function isElement(obj){

   return (typeOf obj === 'object' && !($(obj).html() == undefined));

}
查看更多
情到深处是孤独
3楼-- · 2018-12-31 20:16

You could try appending it to a real DOM node...

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}
查看更多
柔情千种
4楼-- · 2018-12-31 20:16
(element instanceof $ && element.get(0) instanceof Element) || element instanceof Element

This will check for even if it is a jQuery or JavaScript DOM element

查看更多
临风纵饮
5楼-- · 2018-12-31 20:17

The following IE8 compatible, super-simple code works perfectly.

The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.

See it in action here: https://jsfiddle.net/eLuhbu6r/

function isElement(element) {
    return element instanceof Element || element instanceof HTMLDocument;  
}
查看更多
唯独是你
6楼-- · 2018-12-31 20:20

old thread, but here's an updated possibility for ie8 and ff3.5 users:

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}
查看更多
爱死公子算了
7楼-- · 2018-12-31 20:20

For the ones using Angular:

angular.isElement

https://docs.angularjs.org/api/ng/function/angular.isElement

查看更多
登录 后发表回答