jQuery object and DOM element
I would like to understand relationship between jQuery object and DOM element
A jQuery object is an array-like object that contains DOM element(s). A jQuery object can contain multiple DOM elements depending on the selector you use.
Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?
jQuery functions (a full list is on the website) operate on jQuery objects and not on DOM elements. You can access the DOM elements inside a jQuery function using .get()
or accessing the element at the desired index directly:
$("selector")[0] // Accesses the first DOM element in this jQuery object
$("selector").get(0) // Equivalent to the code above
$("selector").get() // Retrieve a true array of DOM elements matched by this selector
In other words, the following should get you the same result:
<div id="foo"></div>
alert($("#foo")[0]);
alert($("#foo").get(0));
alert(document.getElementById("foo"));
For more information on the jQuery object, see the documentation. Also check out the documentation for .get()
What's the difference between a jQuery object and a DOM element? Difference between .get() and .index()?
The get
method is used to access the DOM elements within a jQuery object:
var allDivs = $("div").get();
In that example, allDivs
will be an array containing all the matched elements (in this case, it would contain every div
element in the DOM).
The index
method returns an integer that tells you the position of the selected element relative to its siblings. Consider the following HTML:
<ul>
<li>1</li>
<li id="second">2</li>
<li>3</li>
</ul>
And the following jQuery:
console.log($("#second").index()) //Prints "1"
As for your other question, a DOM node is pretty much anything in the DOM. Elements are types of nodes (type 1). You also have, for example, text nodes (type 3). An element is pretty much any tag.
To make that clearer, consider the following HTML:
<div id="example">
Some text
<div>Another div</div>
<!--A comment-->
</div>
And the following JS:
var div = $("#example").get(0);
for(var i = 0; i < div.childNodes.length; i++) {
console.log(div.childNodes[i].nodeType);
}
That will print out:
3 - Text node ("Some text")
1 - Element node (div)
3 - Text node ("Another div")
8 - Comment node (<!-- -->)
3 - Text node ("A comment")
You can find a list of node types here. For an excellent introduction to what the DOM actually is, see this MDN article
JavaScript DOM object to jQuery object
var $this = $(myObject);
$this
is a jQuery object. You can create jQuery objects from DOM elements.
<tr onclick="changeStatus(this)">
function changeStatus(myObject) {
$(myObject).removeClass();
}
I would like to recommend doing your event binding with jQuery as well:
<tr class="change-status">
$('.change-status').on('click', function () {
$(this).removeClass( ... );
});
This is nice because now all the JS code is in one place and can be updated (in my opinion) more easily. Note that the class I added to the <tr>
element is not necessary if you want to bind to all <tr>
elements in the DOM.
Detect DOM object vs. jQuery Object
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
}
Adding multiple jQuery/DOM elements to single jQuery object
jQuery does allow you to add a bunch of elements at once to a jquery object, but only when those elements are pure DOM elements, not jquery objects themselves.
var $e1 = $('#x'),
$e2 = $('#y'),
$e3 = $('#z');
var e1 = $e1[0],
e2 = $e2[0],
e3 = $e3[0];
>>> $( [$el, $e2, $e3] ) // does not work
[[div], [div], [div]] // jquery object that contains other jQuery objects
>>> $( [el, e2, e3] ) // works
[div, div, div] // jquery object that contains pure DOM objects
When we pass an array of jquery objects to jQuery()
, they are NOT "unwrapped" before adding them to the result jquery object.
Also remember, however, that passing a single jquery object makes the unwrapping happen.
>>> $( $e1 )
[div] // returns a jquery object
Interestingly, if we mix jquery and pure DOM objects, only the pure objects are operated upon:
>>> $( [$e1, e2, $e3] ).css('background-color', '#000');
Note above that second element is a pure DOM element and the background color is only applied to that second element.
The bottom line is: if you want to add multiple elements to a jquery object at once, add pure DOM object, not jquery objects.
How can I convert a DOM element to a jQuery element?
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Raw DOM element vs. jQuery object
The code does not call prepend
on elem
, it calls it on $(elem)
making it a jquery object.
Get HTML String for jQuery and/or DOM object
try the dom property .outerHTML
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>
Related Topics
How to Efficiently Randomly Select Array Item Without Repeats
Foreach on Queryselectorall Not Working in Recent Microsoft Browsers
Prevent Scroll Bubbling from Element to Window
How Filereader.Readastext in HTML5 File API Works
How to Find the Size of Localstorage
Links in <Select> Dropdown Options
Why Does Usestate Cause the Component to Render Twice on Each Update
JavaScript Get Xpath of a Node
Sending Emails with JavaScript
Why Is Value Undefined at .Then() Chained to Promise
How to Sort Elements by Numerical Value of Data Attribute
How to Format/Tidy/Beautify in JavaScript