Chapter 4. DOM Manipulation Methods

Washed his hands of a deadly fate

He put himself in an altered state

—Devo,

"Mecha-mania Boy"

All of the methods in this chapter manipulate the DOM in some manner. A few of them simply change one of the attributes of an element, while others set an element's style properties. Still others modify entire elements (or groups of elements) themselves—inserting, copying, removing, and so on.

A few of these methods such as .attr(), .html(), and .val() also act as getters, retrieving information from DOM elements for later use.

General Attributes

.attr(attribute)

Gets the value of an attribute for the first element in the set of matched elements.

.attr(attribute)
  

Parameters
  • attribute: The name of the attribute to get

Return Value

A string containing the attribute value.

Description

We can get any attribute of an element rather easily without jQuery, by using the native JavaScript function getAttribute. Additionally, most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are:

  • className

  • tagName

  • id

  • href

  • title

  • rel

  • src

Let's consider the following link:

<a id="myid" href="/archives/jquery-links.htm" title="A few jQuery links from long ago">old jQuery links</a>

Using jQuery's .attr method to get an element's attribute has two main advantages:

  1. Convenience: it can be chained to a jQuery object.

  2. Cross-browser consistency: The .attr method always gets the actual attribute text, regardless of which browser is being used. On the other hand, when using getAttribute() with attributes such as href, src, and cite, some browsers (correctly) get the attribute text, while others get the absolute URL, regardless of whether the attribute has an absolute URL or a relative one.

In order to use getAttribute() or any of an element's properties as a substitute for .attr(), we need to make sure that we are working with a DOM node rather than a jQuery object. To convert the first element represented in a jQuery object to a DOM node, we can use either [0] or .get(0).

All of the following use getAttribute('title') to get its title attribute:

  1. document.getElementById('myid').getAttribute('title')

  2. $('#myid').get(0).getAttribute('title')

  3. $('#myid')[0].getAttribute('title')

With any of these options, we could replace .getAttribute('title') with .title.

.attr()

Sets one or more attributes for the set of matched elements.

.attr(attribute, value)
.attr(map)
.attr(attribute, function)
  

Parameters (first version)
  • attribute: The name of the attribute to set

  • value: A value to set for the attribute

Parameters (second version)
  • map: A map of attribute-value pairs to set

Parameters (third version)
  • attribute: The name of the attribute to set

  • function: A function returning the value to set

Return Value

The jQuery object, for chaining purposes.

Description

The .attr method is a convenient and powerful way to set the value of attributes especially when setting multiple attributes or values returned by a function. Let's consider the following image:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller" />
.attr(attribute, value)

We change the alt attribute by putting 'alt' followed by a comma and the new value inside the .attr method's parentheses:

$('#greatphoto').attr('alt', 'Beijing Brush Seller'),

We can add an attribute in the same way:

$('#greatphoto').attr('title', 'Beijing Brush Seller photo by Kelly Clark'),
.attr({map})

To change the alt attribute and add the title attribute at the same time, we can pass both sets of names and values into the method at once using a map (JavaScript object syntax). We join each attribute to its value with a colon and separate each pair with a comma:

$('#greatphoto').attr({alt:'Beijing Brush Seller', title: 'Beijing Brush Seller photo by Kelly Clark'});

When setting multiple attributes, the quotation marks around the attribute names are optional.

.attr(attribute, function)

By using a function to set attributes, we can concatenate a new value with an existing value:

$('#greatphoto').attr({alt: function() {return 'Beijing ' + this.alt}, title: function() {return 'Beijing ' + this.alt + ' photo by Kelly Clark'}});

This use of a function can be even more useful when we apply the attributes to multiple elements.

.removeAttr()

Removes an attribute from each element in the set of matched elements.

.removeAttr(attribute)
  

Parameters
  • attribute: An attribute

Return Value

The jQuery object, for chaining purposes.

Description

The .removeAttr method uses the JavaScript removeAttribute function, but it has the advantage of being able to be chained to a jQuery selector expression.

Style Properties

.css(property)

Gets the value of a style property for the first element in the set of matched elements.

.css(property)
  

Parameters
  • property: A CSS property

Return Value

A string containing the CSS property value.

Description

The .css method is a convenient way to get a style property from the first matched element, especially in the light of the different terms browser's use for certain properties. For example, Internet Explorer's DOM implementation refers to the float property as styleFloat, while Mozilla-based browsers refer to it as cssFloat. The .css method accounts for such differences, producing the same result no matter which term we use. For example, an element that is floated left will return the string left for each of the following three lines:

  1. $('div.left').css('float');

  2. $('div.left').css('cssFloat');

  3. $('div.left').css('styleFloat');

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').

.css()

Sets one or more CSS properties for the set of matched elements.

.css(property, value)
.css(map)
.css(property, function)
  

Parameters (first version)
  • property: A CSS property name

  • value: A value to set for the property

Parameters (second version)
  • map: A map of property-value pairs to set

Parameters (third version)
  • property: A CSS property name

  • function: A function returning the value to set

Return Value

The jQuery object, for chaining purposes.

Description

As with the .attr method, the .css method makes setting properties of elements quick and easy. This method can take either a comma-separated key-value pair or a map of colon-separated key-value pairs (JavaScript object notation).

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({'background-color':'#ffe', 'border-left': '5px solid #ccc'}) and .css({backgroundColor:'#ffe', borderLeft: '5px solid #ccc'}). Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

Since the .css method calls the .attr method internally, we can also pass a function as the property value:

$('div.example').css('width', function(index) {
return index * 50;
});

This example sets the widths of the matched elements to incrementally larger values.

.height()

Gets the current computed height for the first element in the set of matched elements.

.height()
  

Parameters

None.

Return Value

The height of the element, in pixels.

Description

The difference between .css('height') and .height() is that the latter returns a unit‑less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height method is recommended when an element's height needs to be used in a mathematical calculation.

.height(value)

Sets the CSS height of each element in the set of matched elements.

.height(value)
  

Parameters
  • value: An integer representing the number of pixels, or an integer with an optional unit of measure appended

Return Value

The jQuery object, for chaining purposes.

Description

With .height('value'), unlike with .css('height','value'), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit.

.width()

Gets the current computed width for the first element in the set of matched elements.

.width()
  

Parameters

None.

Return Value

The width of the element, in pixels.

Description

The difference between .css(width) and .width() is that the latter returns a unit‑less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width method is recommended when an element's width needs to be used in a mathematical calculation.

.width(value)

Sets the CSS width of each element in the set of matched elements.

.width(value)
  

Parameters
  • value: An integer representing the number of pixels, or an integer along with an optional unit of measure appended

Return Value

The jQuery object, for chaining purposes.

Description

With .width('value'), unlike with .css('width','value'), the value can be either a string (number and unit) or a number. If only a number is provided for the value, jQuery assumes a pixel unit.

Class Attribute

.addClass()

Adds one or more classes to each element in the set of matched elements.

.addClass(class)
  

Parameters
  • class: One or more class names to be added to the class attribute of each matched element

Return Value

The jQuery object, for chaining purposes.

Description

It's important to note that this method does not replace a class; it simply adds the class.

More than one class may be added at a time, separated by a space, to the set of matched elements, like so: $('p').addClass('myclass yourclass').

This method is often used with .removeClass() to switch elements' classes from one to another, like so:

$('p').removeClass('myclass noclass').addClass('yourclass')

Here, the myclass and noclass classes are removed from all paragraphs, while yourclass is added.

.removeClass()

Removes one or all classes from each element in the set of matched elements.

.removeClass([class])
  

Parameters
  • class (optional): A class name to be removed from the class attribute of each matched element

Return Value

The jQuery object, for chaining purposes.

Description

If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

More than one class may be removed at a time, separated by a space, from the set of matched elements, like so: $('p').removeClass('myclass yourclass').

This method is often used with .addClass() to switch elements' classes from one to another, like so:

$('p').removeClass('myclass').addClass('yourclass')

Here, the class myclass is removed from all the paragraphs, while yourclass is added.

To replace all existing classes with another class, use .attr('class','new-class') instead.

.toggleClass()

If the class is present, .toggleClass() removes it from each element in the set of matched elements; if it is not present, it adds the class.

.toggleClass(class)
  

Parameters
  • class: A class name to be toggled in the class attribute of each element in the matched set

Return Value

The jQuery object, for chaining purposes.

Description

This method takes one or more class names as its parameter. If an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass() to a simple <div>:

<div class="tumble">Some text.</div>

The first time we apply $('div.tumble').toggleClass('bounce'), we get the following:

<div class="tumble bounce">Some text.</div>

The second time we apply $('div.tumble').toggleClass('bounce'), the <div> class is returned to the single tumble value:

<div class="tumble">Some text.</div>

Applying .toggleClass('bounce spin') to the same <div> alternates between <div class="tumble bounce spin'> and <div class="tumble'>.

DOM Replacement

.html()

Gets 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 the .html method 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 this code:

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

In order for the following <div> tag's content 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(HTML)

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

.html(HTML)
  

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

Return Value

The jQuery object, for chaining purposes.

Description

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

When we use .html(HTML) to set elements' contents, any contents that were in those elements is completely replaced by the new contents. Consider the following HTML:

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

We can set the HTML contents of <div class="demo-container"> like so:

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

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

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

.text()

Gets 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, the .text method 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:

<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 Boxlist item 1list item 2

.text(text)

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

.text(text)
  

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

Return Value

The jQuery object, for chaining purposes.

Description

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

We need to be aware that this method replaces < and > with &lt; and &gt;, respectively. Consider the following HTML:

<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 HTML:

<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, like this:

<p>This is a test</p>

.val()

Gets 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.

Description

The .val method is primarily used to get the value of form elements.

.val(value)

Sets the value of each element in the set of matched elements.

.val(value)
  

Parameters
  • value: A string of text to set as the value property of each matched element

Return Value

The jQuery object, for chaining purposes.

Description

This method is typically used to set the value of form fields.

DOM Insertion, Inside

.prepend()

Inserts content, specified by the parameter, at the beginning of each element in the set of matched elements.

.prepend(content)
  

Parameters
  • content: An element, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements

Return Value

The jQuery object, for chaining purposes.

Description

The .prepend and .prependTo methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description.prepend()about

We can insert an HTML structure into the beginning of <div class="demo-box"> like so:

$('div.demo-box').prepend('<div class="insertion">This text was <strong>inserted</strong></div>'),

The new <div> and <strong> elements as well as the text nodes are created on the fly and added to the DOM. The result is a new <div> positioned just before the Demonstration Box text:

Description.prepend()about

An element (or array of elements) that already exists on the page could be moved to the beginning of <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('div.demo-box').prepend( $('p:eq(0)') );

.prependTo()

Inserts every element in the set of matched elements at the beginning of the target.

.prependTo(target)
  

Parameters
  • target: A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter

Return Value

The jQuery object, for chaining purposes.

Description

The .prepend and .prependTo methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .prepend(), the selector expression preceding the method is the container into which the content is inserted. With .prependTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

Using .prependTo(), we can insert an HTML structure into the beginning of <div class="demo-box"> like so:

$('<div class="insertion">This text was <strong>inserted</strong> </div>').prependTo('div.demo-box'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned just before the Demonstration Box text:

Description

An element (or array of elements) that already exists on the page could be moved to the beginning of <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a selector expression both for the content to be inserted and for the target:

$('p:eq(0)').prependTo('div.demo-box'),

.append()

Inserts content specified by the parameter at the end of each element in the set of matched elements.

.append(content)

Parameters
  • content: A selector, element, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.

Return Value

The jQuery object, for chaining purposes.

Description

The .append and .appendTo methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

We can insert an HTML structure into the end of <div class="demo-box"> like so:

$('div.demo-box').append('<div class="insertion">This text was <strong>inserted</strong></div>'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned just after the Demonstration Box text:

Description

An element (or array of elements) that already exists on the page could be moved to the end of <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('div.demo-box').append( $('p:eq(0)') );

.appendTo()

Inserts every element in the set of matched elements at the end of the target.

.appendTo(target)
  

Parameters
  • target: A selector, element, HTML string, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter

Return Value

The jQuery object, for chaining purposes.

Description

The .append and .appendTo methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

Using .appendTo(), we can insert an HTML structure into the end of <div class="demo-box"> like so:

$('<div class="insertion">This text was <strong>inserted</strong> </div>').appendTo('div.demo-box'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned just after the Demonstration Box text:

Description

An element (or array of elements) that already exists on the page could be moved to the end of <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a selector expression both for the content to be inserted and for the target:

$('p:eq(0)').appendTo('div.demo-box'),

DOM Insertion, Outside

.before()

Inserts content specified by the parameter before each element in the set of matched elements.

.before(content)
  

Parameters
  • content: An element, HTML string, or jQuery object to insert before each element in the set of matched elements

Return Value

The jQuery object, for chaining purposes.

Description

The .before and .insertBefore methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .before(), the selector expression preceding the method is the container into which the content is inserted. With .insertBefore(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

We can insert an HTML structure before <div class="demo-box"> like so:

$('div.demo-box').before('<div class="insertion">This text was <strong>inserted</strong></div>'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned outside of, just before, <div class="demo-box">:

Description

An element (or array of elements) that already exists on the page could be moved to the DOM position just before <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('div.demo-box').before( $('p:eq(0)') );

.insertBefore()

Inserts every element in the set of matched elements before the set of elements specified in the parameter.

.insertBefore(content)
  

Parameters
  • content: A selector or element before which the matched set of elements will be inserted

Return Value

The jQuery object, for chaining purposes.

Description

The .before and .insertBefore methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .before(), the selector expression preceding the method is the container into which the content is inserted. With .insertBefore(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted before the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

We can insert an HTML structure just before <div class="demo-box"> like so:

$('<div class="insertion">This text was <strong>inserted</strong> </div>').insertBefore('div.demo-box'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned outside of, just before, <div class="demo-box">:

Description

An element (or array of elements) that already exists on the page could be moved to the DOM position just before <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('p:eq(0)').insertBefore('div.demo-box'),

.after()

Inserts content specified by the parameter after each element in the set of matched elements.

.after(content)
  

Parameters
  • content: An element, HTML string, or jQuery object to insert after each element in the set of matched elements.

Return Value

The jQuery object, for chaining purposes.

Description

The .after and .insertAfter methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

We can insert an HTML structure after <div class="demo-box"> like so:

$('div.demo-box').after('<div class="insertion">This text was <strong>inserted</strong></div>'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned outside of, just after, <div class="demo-box">:

Description

An element (or array of elements) that already exists on the page could be moved to the DOM position just after <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('div.demo-box').after( $('p:eq(0)') );

.insertAfter()

Inserts every element in the set of matched elements after the set of elements specified in the parameter.

.insertAfter(content)
  

Parameters
  • content: A selector or element after which the matched set of elements will be inserted

Return Value

The jQuery object, for chaining purposes.

Description

The .after and .insertAfter methods perform the same task. The only difference is in the syntax—specifically, in the placement of the content and target. With .after(), the selector expression preceding the method is the container after which the content is inserted. With .insertAfter(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted after the target container.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

Using .insertAfter(), we can insert an HTML structure after <div class="demo-box"> like so:

$('<div class="insertion">This text was <strong>inserted</strong> </div>').insertAfter('div.demo-box'),

The new <div> and <strong> elements, as well as the text nodes, are created on the fly and added to the DOM. The result is a new <div> positioned outside of, just after, <div class="demo-box">:

Description

An element (or array of elements) that already exists on the page could be moved to the DOM position just after <div class="demo-box"> as well. The following code, for example, moves the document's first paragraph by using a jQuery object:

$('p:eq(0)').insertAfter('div.demo-box'),

DOM Insertion, Around

.wrap()

Wraps a structure of elements around each element in the set of matched elements.

.wrap(html)
.wrap(element)
  

Parameters (first version)
  • html: A string of HTML tags to wrap around the set of matched elements

Parameters (second version)
  • element: An existing element to wrap around the set of matched elements

Return Value

The jQuery object, for chaining purposes.

Description

Note: The HTML must include only well-formed, valid element structures. If any text is included, or if any tags are left unclosed, the .wrap() will fail.

Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

Using .wrap(), we can insert an HTML structure around <div class="demo-box"> like so:

$('div.demo-box').wrap('<div class="insertion"> </div>'),

The new <div> element is created on the fly and added to the DOM. The result is a new <div> wrapped around <div class="demo-box">:

Description

Using a DOM node as our parameter instead, we could wrap the new <div> around an element with id="demo-box1" like so:

$(document.getElementById('demo-box1')).wrap(' <div class="insertion"> </div>'),

DOM Copying

.clone()

Creates a copy of the set of matched elements.

.clone([deep])
  

Parameters
  • deep (optional): A Boolean. Default is true. If set to false, the .clone method copies only the matched elements themselves, excluding any child/descendant elements and text.

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:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

To copy <div class="demo-box"> and paste that copy after the original, we could write the following:

$('div.demo-box:last').clone().insertAfter('div.demo-box:last'),

Now we have Demonstration Box twice:

Description

Notice that we use the :last selector here so that we are sure to only copy (.clone()) and paste (.insertAfter()) a single copy. We need to be aware of the potential to inadvertently clone or insert more than we intend, and take the necessary precautions to prevent that from occurring.

Note

With the .clone method, we can modify the cloned elements or their contents before inserting them into the document.

The optional deep parameter accepts a Boolean—true or false. Since in most cases we want to clone child nodes as well, and since the default is true, the parameter is rarely used. However, imagine that we wanted to copy the Demonstration Box without its text and then append a paragraph to every <div class="demo-box">. We could make this happen with the following code:

$('div.demo-box:last').clone(false).insertAfter('div.demo-box:last'),
$('div.demo-box').append('<p>New Message</p>);

Now the two boxes look like this:

Description

The first box now has both the original Demonstration Box text and the additional New Message text while the new, cloned box has only the additional text.

DOM Removal

.empty()

Removes 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, any string of text within an element is considered a child node of that element. Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

If we apply $('div.demo-box').empty(); to it, the Demonstration Box text string is removed:

Description

If we had any number of nested elements inside <div class="demo-box">, they would be removed, too.

.remove()

Removes the set of matched elements from the DOM.

.remove([selector])
  

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

Return Value

The jQuery object, for chaining purposes.

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. Consider the following HTML:

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

The two <div>s, with a little CSS, are rendered on the right side of the page as follows:

Description

If we apply $('div.demo-box').remove() to it, the entire <div class="demo-box> along with everything in it is removed:

Description

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows: $('div').remove('.demo-box'). Or, if we had multiple elements with the same class name and wanted to remove only the first one the one with id="temporary-demo-box", we could write the following:

$('div.demo‑box').remove('#temporary-demo-box ').
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.231.155