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.
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.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With