0

I tried to find out which is a dom object or which is a javascript object

var domObj =document.getElementById('lga');

typeof domObj

"object"

var jsObj = {name:"BP"}

typeof jsObj

"object"

Then how do I identify which is a dom object or js object.

3
  • DOM objects are javascript objects if accessing them via javascript. Commented Dec 11, 2013 at 18:27
  • so what you really want to know is "is some object a DOM object or not a DOM object?" Commented Dec 11, 2013 at 18:27
  • jQuery only does else if ( selector.nodeType ). Of course you will get false positives if a normal object has such a property. Commented Dec 11, 2013 at 18:29

2 Answers 2

4

You can use

domObj instanceof HTMLElement; // true

It will be false for

jsObj instanceof HTMLElement; // false

In an if it would look like this

if (domObj instanceof HTMLElement) {
  // ...
}
else {
  // ...
}

You can learn more about your objects by inspecting their constructor property

document.body.constructor; // function HTMLBodyElement() { [native code] }
Sign up to request clarification or add additional context in comments.

2 Comments

Good idea. Instead of HTMLElement, you could compare to Node if you were also interested in TextNodes, CommentNodes, etc.
domObj instanceof HTMLElement; this works fine in Chrome but not in IE8, domObj instanceof Object; This returns true in Chrome but false in IE8. Is there any specific way to do it crossbrowser.
0

I think this should be of help Javascript isDOM - How do you check if a Javascript Object is a DOM Object

This gives a cross-browser way to handle the requirement, at the same time explaining the underlying implementation of common browsers.
I think this should answer your question on how to identify an object of type HTMLElement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.