How do you check if a JavaScript Object is a DOM Object?
This might be of interest:
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
It's part of the DOM, Level2.
Update 2: This is how I implemented it in my own library:
(the previous code didn't work in Chrome, because Node and HTMLElement are functions instead of the expected object. This code is tested in FF3, IE7, Chrome 1 and Opera 9).
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
//Returns true if it is a DOM element
function isElement(o){
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}
How to check if object is a DOM element?
A DOM element implements the Element
interface. So you can use:
function Check(o) {
alert(o instanceof Element);
}
Checking if object is a DOM-element
To check if it's an element I think obj.nodeName
is your best bet.
var a = new SharedWorker("bigdatahandler.js");
if (!s.nodeName) {
a.postMessage(s);
}
You can also check s instanceof Element
, because you don't need to support IE I guess :)
To check if it's part of the DOM:
function inDOM(elem) {
do {
if (elem == document.documentElement) {
return true;
}
} while (elem = elem.parentNode)
return false;
}
What's the best way to detect if a given Javascript object is a DOM Element?
jQuery checks the nodeType property. So you would have:
var overloaded = function (arg) {
if (arg.nodeType) {
// Code for DOM Element argument...
}
};
Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:
var overloaded = function (arg) {
if (arg.nodeType && arg.nodeType == 1) {
// Code for DOM Element argument...
}
};
How do you check if a JavaScript Object is a new DOM Element?
How about checking for the outerHTML
?
var testBlock = { mutationToDom: function() { var container = document.createElement('mutation'); container.setAttribute('string', 'test'); return container; }};
QUnit.test( 'check function mutationToDom', function( assert ) { var container = testBlock.mutationToDom(); assert.ok( container.outerHTML === '<mutation string="test"></mutation>', 'mutation is created with correct value' );});
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.6.0.css"><div id="qunit"></div><div id="qunit-fixture"></div><script src="https://code.jquery.com/qunit/qunit-2.6.0.js"></script>
jQuery - check if variable is dom element
You can use instanceof
to check if the object passed in is an instanceof jQuery
or an instanceof HTMLElement
. If it is return true;
. Otherwise, return false
.
function isDomElem(obj) {
if(obj instanceof HTMLCollection && obj.length) {
for(var a = 0, len = obj.length; a < len; a++) {
if(!checkInstance(obj[a])) {
console.log(a);
return false;
}
}
return true;
} else {
return checkInstance(obj);
}
function checkInstance(elem) {
if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) {
return true;
}
return false;
}
}
Optionally, instead of returning true
or false
, you could do some other action. You could also split each option out and do a separate action depending on which one the object is an instance of jQuery
or HTMLElement
. You have lots of choices to choose from.
$(function () { var temp1 = $('div'), temp2 = $('div')[0], temp3 = "foo", temp4 = ['bar'], temp5 = $('span'), temp6 = document.getElementsByClassName("test"); alert(isDomElem(temp1)); alert(isDomElem(temp2)); alert(isDomElem(temp3)); alert(isDomElem(temp4)); alert(isDomElem(temp5)); alert(isDomElem(temp6)); function isDomElem(obj) { if(obj instanceof HTMLCollection && obj.length) { for(var a = 0, len = obj.length; a < len; a++) { if(!checkInstance(obj[a])) { return false; } } return true; } else { return checkInstance(obj); } function checkInstance(elem) { if((elem instanceof jQuery && elem.length) || elem instanceof HTMLElement) { return true; } return false; } }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div></div><p class="test"></p><p class="test"></p>
How to check if JS object implement some DOM IDL interface?
I'm not quite sure why you want to do this, but it should work in modern browsers. It won't work in IE8 or below.
If your goal is to see whether a node is an Element or a Text node or similar, the more broadly-compatible way is to use the nodeType
property:
document.querySelector('a').nodeType === 1
The types are given by the DOM specs as part of the definition of the Node
interface (1 = Element).
If your goal is to test whether an element is a specific type of element (HTMLAnchorElement
and so on), use nodeName
or (if you know it's an element) tagName
. In an HTML (not XHTML) document, those are upper case tag names, e.g.
console.log(document.querySelector('a').nodeName); // "A"
Related Topics
How to Find the Width of a Div Using Vanilla JavaScript
How to Load Images Dynamically (Or Lazily) When Users Scrolls Them into View
Cropping Images in the Browser Before the Upload
Refresh a Div That Has a Google Ad Inside It
Error: Failed to Execute 'Appendchild' on 'Node': Parameter 1 Is Not of Type 'Node'
Print Specific Part of Webpage
Adding Multiple Event Listeners to One Element
How to Change CSS :Root Color Variables in JavaScript
How to Format/Tidy/Beautify in JavaScript
Jquery $("#Radiobutton").Change(...) Not Firing During De-Selection
What Is the Correct Way to Write HTML Using JavaScript
How to Select Element That Does Not Have Specific Class
Loading an Image to a <Img> from <Input File>