Channels ▼
RSS

Web Development

Manipulating the DOM with jQuery


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:

$(":t;div />", {
                class: "panel",
                text: "Click me!",
                click: function() {
                   $(this).toggleClass("extra");
                }
              }
);

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 after first 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.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

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.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Comments:

Dr. Dobb's TV