Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect DOM object vs. jQuery Object

I have a function that I want to be able to allow passing in either a regular javascript DOM element object or a jQuery object. If its not yet a jQuery object I will then make it one.

Does anyone know of a very reliable way to detect this.

function functionName(elm){    //Detect if elm is not a jquery object in condition    if (elm) elm = $(elm);  } 

A logical approach is to detect one of the properties of the DOM element object. The question is, which property would be the most reliable to detect?

I could also just make it a jquery object either way since jQuery doesn't have a problem with something like: $($imajQueryObjAlready); However, the purpose of this question is not to just solve the problem, but to find a good way to detect if its a DOM object vs. a jQuery object.

like image 429
UpHelix Avatar asked Nov 10 '10 00:11

UpHelix


People also ask

What is the difference between jQuery and DOM?

A DOM element represents a visual or functional element on the page which was created from the original HTML document. jQuery now is a Javascript library that makes manipulating the DOM easier than with pure Javascript by offering a number of convenience shortcuts.

How can I tell if an object is a jQuery object?

Check out the instanceof operator. Show activity on this post. The best way to check the instance of an object is through instanceof operator or with the method isPrototypeOf() which inspects if the prototype of an object is in another object's prototype chain.

What is a DOM object jQuery?

The Document Object Model (DOM for short) is a representation of an HTML document. It may contain any number of DOM elements. At a high level, a DOM element can be thought of as a "piece" of a web page. It may contain text and/or other DOM elements.

How do I pull a native DOM element from a jQuery object?

Use the get() method. However, most of the time you want to use jQuery methods to do the manipulation as opposed to getting access to the raw DOM element and then modifying it using "standard" JavaScript. For example, with jQuery you can just say $('mySelector'). addClass('myClass') to add a CSS class to a DOM element.


1 Answers

To test for a DOM element, you can check its nodeType property:

if( elm.nodeType ) {     // Was a DOM node } 

or you could check the jQuery property:

if( elm.jquery ) {     // Was a jQuery object } 
like image 162
user113716 Avatar answered Sep 18 '22 15:09

user113716