Web Development

Manipulating the DOM with jQuery

By Dino Esposito, March 09, 2011

JQuery offers the ability to select a plain chunk of HTML and get the resulting DOM tree

One of the factors for the success of the jQuery library is its ability to work with the Document Object Model (DOM) in a way that is both powerful and easy to code. In which way is jQuery different (and largely preferable over) the standard DOM API?

The standard DOM provides a rich set of methods to create HTML trees dynamically. It turns out, however, that in nearly all browsers the performance of native DOM objects is poor compared to using the innerHTML property, which is not officially part of the DOM standard. While functions and objects to neatly compose a piece of HTML are great things to have, the ability to select a plain chunk of HTML and get the resulting DOM tree is even more compelling. In jQuery, you find an API that supports both approaches with a syntax that is more compact and developer-friendly. Let's see what it takes to create a DOM tree.

The simplest way to create a new DOM tree in jQuery consists of passing an HTML string to the jQuery (or $) function, as shown here:

$(":t;ul>:t;li>Joe:t;/li>:t;li>Bob:t;/li>");

In the HTML, you pass as a string; you can also indicate style information, event handlers, and set attributes. The following example builds a DOM object that consists of a DIV element with some inner text, a CSS class, and a click handler:

It should be noted that the DOM you create in this way is not part of the page as yet. To add it to the existing page DOM, an additional step is required.

The jQuery library defines a bunch of functions to attach an in-memory DOM tree to an existing DOM. The following code shows how to insert a dynamically created image after each element of a wrapped set. The wrapped set includes all LI child elements of a UL element identified by name:

$("#PlayerList li").after(":t;img src='unknown.jpg' />");

The function named afterfirst creates an in-memory DOM from the provided markup and then inserts it after any matching element within the wrapped set. The function after places the DOM following the insertion point; other functions offer alternate options. For example, as a developer, you can rely on methods like before, prepend, and append. The function prepend puts the DOM before the inner text of matching elements, whereas the function append puts the DOM right after the inner text of matching elements.

In all examples we've considered so far, the existing DOM imports a dynamically created tree. You can also add elements to an existing DOM the other way around — that is, by first creating the new DOM and then inserting it in some way around elements in a wrapped set. In this case, you use insertAfter and insertBefore to insert a DOM after or before the elements identified by the specified selector:

$(html).insertAfter(selector);
$(html).insertBefore(selector);

You use the prependTo and appendTo functions to insert something before and after, respectively, the inner text of a matching element:

$(html).prependTo(selector);
$(html).appendTo(selector);

The jQuery library also makes it easy to detach an existing DOM tree. All you need is a call to the method detach, as shown below.

var h1InSection = $("h1", "#section").detach();

Detaching a DOM tree doesn't really destroy it. A detached DOM tree is still referenced in memory. It is treated like a dynamically created DOM tree that is not bound to the current page upon creation. As a result, you can detach a tree from one place and insert it elsewhere, thus creating a nice animation. To remove and destroy elements from the DOM, you resort to the remove method:

$(selector).remove();

Another option is using the empty function. The empty function is designed to just empty the body of each element selected by the query expression:

$(selector).empty();

DOM manipulation is an important practice in rich client-side applications because it is frequently used and because of the impact it can have on performance. Every time you make a modification to the DOM, the browser needs to reflow the DOM and update the page. If done too often, it will have a serious impact on the page. Using detached trees is an excellent workaround as it doesn't limit the changes you can enter but, at the same time, doesn't trigger a DOM refresh each time. The pattern is: Detach the DOM segment you're interested in, apply your changes, and reattach the segment when you're done. It's easy and effective.

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task.
However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

This month's Dr. Dobb's Journal

This month,
Dr. Dobb's Journal is devoted to mobile programming. We introduce you to Apple's new Swift programming language, discuss the perils of being the third-most-popular mobile platform, revisit SQLite on Android
, and much more!