Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

3.3. Convert a Selected jQuery Object into a Raw DOM Object

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];.

Warning

We are discussing the core .get() method, which transforms a jQuery object to a DOM array. We are not discussing the Ajax get method, which will load a remote page using an HTTP GET request.

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 innerHTML of an element:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required