Convert a Selected jQuery Object into a Raw DOM Object - J Query

Problem
Selecting elements on a page with jQuery returns a set as a jQuery object and not as a raw DOM object. Because it’s a jQuery object, you can only run jQuery methods against the selected set. To be able to run DOM methods and properties against the selected set, the set needs to be converted to a raw DOM object.

Solution

jQuery provides a core method get(), which will convert all matched jQuery objects back into an array of DOM objects. Additionally, you can pass an index value in as an argument of get(), which will return the element at the index of the matched set as a DOM object, $.get(1);. Now, even though you can get at a single element’s DOM object via $.get(index), it is there for historical reasons; the “best practices” way is to use the [] notation, $("div")[1];.
Because get() returns an array, you can traverse the array to get at each DOM element.Once it’s a DOM element, you can then call traditional DOM properties and methods against it. Let’s explore a simple example of pulling the inner HTML of an element:

Because get() returns an array, you can traverse the array to get at each DOM element. Once it’s a DOM element, you can then call traditional DOM properties and methods against it. Let’s explore a simple example of pulling the inner HTML of an element:

Convert-a-Selected-jQuery-Object-into-a-Raw-DOM-Object

Figure : shows the output.

We start by selecting all the <div>elements on the page and calling [0]. We pass in the index of the selection we want to work with; since there is only one <div>on the page,we can pass in index 0. Finally, we call a property, in this case inner HTML, to retrieve the raw DOM element.

Discussion

The core get() method can be very useful, as there are some non-JavaScript methods that we can utilize for our advantage. Let’s say we have a list and we need to show that list in reverse order. Since get() returns an array, we can use native array methods to reverse sort the list and then redisplay the list:

Convert-a-Selected-jQuery-Object-into-a-Raw-DOM-Object

Figure : shows the output.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics