jQuery 1.4 DOM Manipulation Methods for Replacement, Copying and Removal

Exclusive offer: get 80% off this eBook here
jQuery Reference Guide

jQuery Reference Guide — Save 80%

A Comprehensive Exploration of the Popular JavaScript Library

₨587.06    ₨117.41
by Jonathan Chaffer Karl Swedberg | February 2010 | AJAX Open Source Web Development

All of the methods in this article by Karl Swedberg and Jonathan Chaffer, authors of jQuery 1.4 Reference Guide, manipulate the DOM in some manner. In a previous article we saw methods that simply change one of the attributes of an element, while others set an element's style properties. Later we saw DOM Insertion methods. In this article we cover methods that modify entire elements (or groups of elements) themselves by replacment, copying, and removal. All of these methods are referred to as setters, as they change the values of properties. A few of these methods such as .html(), .val() also act as getters, retrieving information from DOM elements for later use.

DOM replacement

These methods are used to remove content from the DOM and replace it with new content.

.html() (getter)

Get the HTML contents of the first element in the set of matched elements.

.html()

Parameters

None

Return value

A string containing the HTML representation of the element.

Description

This method is not available on XML documents.

In an HTML document, we can use .html() to get the contents of any element. If our selector expression matches more than one element, only the first one's HTML content is returned. Consider the following code:

$('div.demo-container').html();

In order for the content of the following <div> to be retrieved, it would have to be the first one in the document.

<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>

The result would look like this:

<div class="demo-box">Demonstration Box</div>

.html() (setter)

Set the HTML contents of each element in the set of matched elements.

.html(htmlString)
.html(function)

Parameters (first version)

  • htmlString: A string of HTML to set as the content of each matched element

Parameters (second version)

  • function: A function returning the HTML content to set

Return value

The jQuery object, for chaining purposes.

Description

The .html() method is not available in XML documents.

When we use .html() to set the content of elements, any content that was in those elements is completely replaced by the new content. Consider the following HTML code:

<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>

We can set the HTML contents of <div class="demo-conta iner"> as follows:

$('div.demo-container')
.html('<p>All new content. <em>You bet!</em></p>');

That line of code will replace everything inside <div class="demo-container">.

<div class="demo-container">
<p>All new content. <em>You bet!</em></p>
</div>

As of jQuery 1.4, the .html() method allows us to set the HTML content by passing in a function.

$('div.demo-container').html(function() {
var emph = '<em>' + $('p').length + ' paragraphs!</em>';
return '<p>All new content for ' + emph + '</p>';
});

Given a document with six paragraphs, this example will set the HTML of <div class="demo-container"> to <p>All new content for <em>6 paragraphs!</em></p>.

.text() (getter)

Get the combined text contents of each element in the set of matched elements, including their descendants.

.text()

Parameters

None

Return value

A string containing the combined text contents of the matched elements.

Description

Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the combined text of all matched elements. Consider the following HTML code:

<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>

The code $('div.demo-container').text() would produce the following result:

Demonstration Box list item 1 list item 2

.text() (setter)

Set the content of each element in the set of matched elements to the specified text.

.text(textString)
.text(function)

Parameters (first version)

  • textString: A string of text to set as the content of each matched element

Parameters (second version)

  • function: A function returning the text to set as the content

Return value

The jQuery object, for chaining purposes.

Description

Unlike the .html() method, .text() can be used in both XML and HTML documents.

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as &lt; for <). Consider the following HTML code:

<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>

The code $('div.demo-container').text('<p>This is a test.</p>'); will produce the following DOM output:

<div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div>

It will appear on a rendered page as though the tags were exposed as follows:

<p>This is a test</p>

As of jQuery 1.4, the .text() method allows us to set the text content by passing in a function.

$('ul li').text(function() {
return 'item number ' + ($(this).index() + 1);
});

Given an unordered list with three <li> elements, this example will produce the following DOM output:

<ul>
<li>item number 1</li>
<li>item number 2</li>
<li>item number 3</li>
</ul>
jQuery Reference Guide A Comprehensive Exploration of the Popular JavaScript Library
Published: July 2007
eBook Price: ₨587.06
Book Price: ₨325.00
See more
Select your format and quantity:

.val() (getter)

Get the current value of the first element in the set of matched elements.

.val()

Parameters

None

Return value

A string containing the value of the element, or an array of strings if the element can have multiple values.

Description

The .val() method is primarily used to get the values of form elements. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.

.val() (setter)

Set the value of each eleme nt in the set of matched elements.

.val(value)
.val(function)

Parameters (first version)

  • value: A string of text or an array of strings to set as the val ue property of each matched element

Parameters (second version)

  • function: A function returning the value to set

Return value

The jQuery object, for chaining purposes.

Description

This method is typically used to set the values of form fields. For <select multiple="multiple"> elements, multiple <option> can be selected by passing in an array.

The .val() method allows us to s et the value by passing in a function.

$('input:text.items').val(function() {
return this.value + ' ' + this.className;
});

This example appends the string "items" to the text inputs' values.

.replaceWith()

Replace each element in the set of matched elements with the provided new content.

.replaceWith(newContent)

Parameters

  • newContent: The content to insert. This might be an HTML string, a DOM element, or a jQuery object.

Return value

The jQuery object, for chaining purposes. See the following section for details.

Description

The .replaceWith() method allows us to remove content from the DOM and insert new content in its place with a single call. Consider this DOM structure:

<div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div>

We can replace the second inner <div> with specified HTML.

$('.second').replaceWith('<h2>New heading</h2>');

This results in the following structure:

<div class="container">
<div class="inner first">Hello</div>
<h2>New heading</h2>
<div class="inner third">Goodbye</div>
</div>

We could equally target all inner <div> elements at once.

$('.inner').replaceWith('<h2>New heading</h2>');

This causes all of them to be replaced.

<div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div>

Alternatively, we could select an element to use as the replacement.

$('.third').replaceWith($('.first'));

This results in the following DOM structure:

<div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, and not by being cloned.

The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

.replaceAll()

Replace each target element with the set of matched elements.

.replaceAll(target)

Parameters

  • target: A selector expression indicating which element(s) to replace

Return value

The jQuery object, for chaining purposes.

Description

The .replaceAll() method is corollary to .replaceWith(), but with the source and target reversed. Consider the following DOM structure:

<div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div>

We can create an element, and then replace other elements with it.

$('<h2>New heading</h2>').replaceAll('.inner');

This causes all of them to be replaced.

<div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div>

Alternatively, we could select an element to use as the replacement:

$('.first').replaceAll('.third');

This results in the following DOM structure:

<div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, and not by being cloned.

jQuery Reference Guide A Comprehensive Exploration of the Popular JavaScript Library
Published: July 2007
eBook Price: ₨587.06
Book Price: ₨325.00
See more
Select your format and quantity:

DOM copying

This method allows us to make copies of elements.

.clone()

Create a copy of the set of matched elements.

.clone([withEvents])

Parameters

  • withEvents (optional): A Boolean indicating whether event handlers should be copied along with the elements

Return value

A new jQuery object referencing the created elements.

Description

The .clone() method, when used in conjunction with one of the insertion methods, is a convenient way to duplicate elements on a page. Consider the following HTML code:

<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>

As shown in the Description for .append(), normally when we insert an element somewhere in the DOM, it is moved from its old location. So, suppose this code is used:

$('.hello').appendTo('.goodbye');

The resulting DOM structure will be as follows:

<div class="container">
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div>

To prevent this and instead create a copy of the element, we could write the following:

$('.hello').clone()
.appendTo('.goodbye');

This will produce the following:

<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div>

Note that when using the .clone() method, we can modify the cloned elements or their contents before (re-)inserting them into the document.

Normally, any event handlers bound to the original element are not copied to the clone. The optional withEvents parameter allows us to change this behavior, and instead make copies of all the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data attached by the .data() method will be copied along with the event handlers.

DOM removal

These methods allow us to delete elements from the DOM.

.empty()

Remove all child nodes of the set of matched elements from the DOM.

.empty()

Parameters

None

Return value

The jQuery object, for chaining purposes.

Description

This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because according to the DOM specification, any string of text within an element is considered a child node of that element. Consider the following HTML code:

<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>

We can target any element for removal.

$('.hello').empty();

This will result in a DOM structure with the "Hello" text deleted.

<div class="container">
<div class="hello"></div>
<div class="goodbye">Goodbye</div>
</div>

If we had any number of nested elements inside <div class="hello">, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

.remove()

Remove the set of matched elements from the DOM.

.remove([selector])

Parameters

  • selector(optional): A selector expression that filters the set of matched elements to be removed

Return value

The jQuery object, for chaining purposes. Note that the removed elements are still referenced by this object, even though they are no longer in the DOM.

Description

Similar to .empty(), the .remove() method takes elements out of the DOM. We use .remove() when we want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

Consider the following HTML code:

<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>

We can target any element for removal.

$('.hello').remove();

This will result in a DOM structure with the <div> element deleted.

<div class="container">
<div class="goodbye">Goodbye</div>
</div>

If we had any number of nested elements inside <div class="hello">, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

$('div').remove('.hello');

This would result in the same DOM structure.

<div class="container">
<div class="goodbye">Goodbye</div>
</div>

.detach()

Remove the set of matched elements from the DOM.

.detach([selector])

Parameters

  • selector (optional): A selector expression that filters the set of matched elements to be removed.

Return value

The jQuery object, for chaining purposes. Note that the removed elements are still referenced by this object, even though they are no longer in the DOM.

Description

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

.unwrap()

Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

.unwrap()

Parameters

None

Return value

The jQuery object, for chaining purposes.

Description

The .unwrap() method removes the element's parent. This is effectively the inverse of the .wrap() method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.

Summary

In this article we have covered DOM manipulation methods for Replacement, Copying and Removal.

If you have read this article you may be interested to view :

About the Author :


Jonathan Chaffer

Jonathan Chaffer is a member of Rapid Development Group, a web development firm located in Grand Rapids, Michigan. His work there includes overseeing and implementing projects in a wide variety of technologies, with an emphasis in PHP, MySQL, and JavaScript. He also leads on-site training seminars on the jQuery framework for web developers.

In the open source community, he has been very active in the Drupal CMS project, which has adopted jQuery as its JavaScript framework of choice. He is the creator of the Content Construction Kit, a popular module for managing structured content on Drupal sites. He is also responsible for major overhauls of Drupal's menu system and developer API reference.

He lives in Grand Rapids with his wife, Jennifer.

Karl Swedberg

Karl Swedberg is a web developer at Fusionary Media in Grand Rapids, Michigan, where he spends much of his time making cool things happen with JavaScript. As a member of the jQuery team, he is responsible for maintaining the jQuery API site at api.jquery.com. He is also a member of jQuery's Board of Advisors and a presenter at workshops and conferences. When he isn't coding, he likes to hang out with his family, roast coffee in his garage, and exercise at the local CrossFit gym.

Books From Packt

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

AJAX and PHP: Building Modern Web Applications 2nd Edition
AJAX and PHP: Building Modern Web Applications 2nd Edition

Backbase 4 RIA Development
Backbase 4 RIA Development

CodeIgniter 1.7
CodeIgniter 1.7

TYPO3 4.3 Multimedia Cookbook
TYPO3 4.3 Multimedia Cookbook

Learning jQuery 1.3
Learning jQuery 1.3

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software