Jquery Tutorial : Dom Manipulation
- To provide interaction on a page you want to be able manipulate elements dynamically.
In this chapter, you are going to learn how to dynamically:
- Create elements on the page
- Insert existing or freshly created elements on the page
- Move elements to a different location on the page
- Clone elements
- Remove elements
- Replace elements
- From a selection of elements, you will be able to get and/or set their attribute values.
- Manipulating the DOM using jQuery is a common operation you will have to do most of time.
First we’ll focus on the different methods allowing you to create, insert, move, clone, remove, and replace elements in the DOM.
- Later we’ll discuss modifying the content of an element and its attributes.
There are two ways to create elements in jQuery:
Often, the easiest way is to provide a string with HTML markup of the element as the sole argument to the
jQueryfunction:var $menuli1 = $('<li class="menu-li1">Italian Food</li>');Alternatively, you can provide a string with the basic HTML markup as the first argument, and a JavaScript object as the second argument.
-
The object’s properties can specify
text, event callbacks (discussed later), and other HTML attributes. - This is often more convenient when using calculated values for attributes.
var $menuli1 = $('<li/>', { 'class': 'menu-li1', 'text': 'Italian Food' });![[Note]](../images/note.png)
Note It is considered a best practice to put quotes around object property names because some words such as
classare reserved keywords in JavaScript.-
The object’s properties can specify
- Using either method, the result is a jQuery object representing the new element.
Some jQuery programmers follow a convention of using $ as the first character for variable names when those variables contain jQuery objects. Although this naming convention is not universal, we will follow it in this course.
- We have just seen how to create elements. However, these elements have not been inserted into the page yet.
There are many ways to insert elements into a page. Elements can be inserted:
- Before an existing element
- After an existing element
- Inside a container element, at its beginning
- Inside a container element, at its end
Moreover, there are two approaches to each method of inserting elements into a page:
- Place the selected element(s) relative to another element
- Place an element relative to the selected element(s)
.insertBefore()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $menuli1.insertBefore('.menu-li1:first');.before()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $('.menu-li1:first').before($menuli1); // Or... $('.menu-li1:first').before('<li class="menu-li1">Italian Food</li>');
.insertAfter()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $menuli1.insertAfter('.menu-ul2:last');.after()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $('.menu-ul2:last').after($menuli1); // Or... $('.menu-ul2:last').after('<li class="menu-li1">Italian Food</li>');
.prepend()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $('.menu-ul1').prepend($menuli1); // Or... $('.menu-ul1').prepend('<li class="menu-li1">Italian Food</li>');.prependTo()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $($menuli1).prependTo('.menu-ul1');
.append()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $('.menu-ul1').append($menuli1); // Or... $('.menu-ul1').append('<li class="menu-li1">Italian Food</li>');.appendTo()var $menuli1 = $('<li class="menu-li1">Italian Food</li>'); $($menuli1).appendTo('.menu-ul1');
The various insertion methods can result in multiple insertions if the target selection contains more than one element.
For example, the following code results in inserting a new paragraph as the first child of each
<div>in the document:$('div').prepend('<p>A new first paragraph</p>');
The same techniques that we have just discussed for inserting elements into a page, can also be used to move elements.
- The only difference is that the elements to be inserted are the result of a previous selection.
Here are two examples of moving the first element with the class
articleso that it is the last child of the element whose id issection.- Functionally, the only difference is the jQuery object returned by the method. This would be important if this code appeared within chained methods.
In this example, the jQuery object returned is the
sectionelement.$('#section').append($('.article:first'));In this example, the jQuery object returned is the
articleelement.$('.article:first').appendTo($('#section'));
![]() | Note |
|---|---|
If the target selection contains more than one element, the elements being moved are duplicated and inserted into each target. |
- We have just seen how to move elements, but what if we want a copy of those elements?
The
.clone()method creates a “deep copy” of an existing selection.- All descendant elements and text are duplicated.
- You can optionally request replication of event handlers and additional jQuery metadata associated with the original selection.
-
.clone()returns a jQuery object of the duplicate, leaving the original selection in place. For example:
var $article=$('.article:first').clone(); //
$('#section').append($article); // 
- Once you have a selection of elements in the page, you can choose to remove this selection.
There are two methods in jQuery that allow you to remove a selection:
.detach()and.remove().- Those two methods are similar because they both return the removed selection in case you want to restore it later.
The major difference is that when using
.remove(), the selection loses its associated jQuery data and its attached events. This is not the case when using.detach().![[Note]](../images/note.png)
Note Generally, use
.detach()when you want to`reattach'' the selection to the page again in the future; use `.remove()if you intend to discard the selection.
To replace a selection of elements on the page, we can use two methods:
.replaceWith()and.replaceAll().The
.replaceWith()method removes content from the DOM and inserts new content in its place with a single call.$('.menu-li1').each(function(){ $(this).replaceWith('<h3>'+$(this).text()+'</h3>'); });![[Note]](../images/note.png)
Note .replaceWith()returns the original jQuery object (that is, the one just removed from the DOM).The
.replaceAll()method is corollary toreplaceWith(), but with the source and target reversed.$('.menu-li1').each(function(){ $('<h3>'+$(this).text()+'</h3>').replaceAll($(this)); });
There are two methods in jQuery that can be used to get the content of a selection:
The
.html()method that returns the inner html of the first element in a set of matched elements:$('.article').html();The
.text()method that returns the combined text contents of each element in the selection including their descendants:$('.article').text();
Using the same methods, you can set the html or text content of a selection:
The
.html(content_to_insert)treats the content to be inserted as html:$('.header').html("<b>cool</b>");The
.text(content_to_insert)treats the content to be inserted as text:$('.header').text("<b>cool</b>");
![]() | Note |
|---|---|
Do not use the |
To get or set other attributes of an HTML element, use the
.attr()method-
When used as a getter, the
.attr(attribute_name)method only applies to the first element of the selection. -
When used as a setter, the
.attr(attribute_name, attribute_value)method applies to all elements of the selection.
-
When used as a getter, the