CodingBison

jQuery provides several methods for updating DOM elements. Let us begin by listing some of those methods in the following table.


Table: Methods for Managing DOM Element(s)
MethodDescription
.after(x)inserts DOM node (x) after the element(s)
.before(x)inserts DOM node (x) before the element(s)
.after(func form x)inserts DOM node (x) after the element(s)
.before(func form x)inserts DOM node (x) before the element(s)
.insertAfter(t)inserts element(s) after the target DOM node (t)
.insertBefore(t)inserts element(s) before the target DOM node (t)
.replaceWith(x)the descendants of the element(s) that match the passed selector
.replaceAll()the sibling nodes of the passed element(s)
.detach(x)deletes the DOM node (x) from the DOM tree but keeps a copy
.remove(x)removes the DOM node (x) from the DOM tree
.empty()remove all child nodes of the element(s)

To describe the above methods a little better, we can use a simple HTML example. The main thing of interest in this example (provided below) is an ordered list ("<ol>") element that consists of various child list ("<li>") elements.

 <!doctype html>
 <html>
 <body>
 <ol>
     <li id="idPhys" class="twoTimesWinner">Marie Curie</li>
     <li id="idChem" class="twoTimesWinner">Marie Curie</li>
     <li id="idPeace">Mother Teresa</li>
 </ol>
 </body>
 </html>

With that, let us now describe the methods presented in the above table.

The .after() method adds a new DOM node after an element (or elements). Thus, in the above example, if we want to insert a new list element after the list element with CSS id "idPeace", then we can do that as $("#idPeace").after("<li>Peter W. Higgs</li>"). In fact, we can use the same method to insert multiple elements -- we can provide them by placing commands in between: $("#idPeace").after("<li>Peter W. Higgs</li>", "<li>Francois Englert</li>") Further, instead of $("#idPeace"), we can also specify a list of elements and this method will insert the passed content to all those elements. Hence, $(".twoTimesWinneridPeace").after("<li>Peter W. Higgs<li>") will insert the new list element after each element that has the CSS class, "twoTimesWinner".

The .before() method allows us to add a new DOM node before an element (or elements). Thus, in the above example, $("#idPeace").before("<li>Peter W. Higgs</li>") would insert a new list element before the list element with CSS id "idPeace". Likewise, the following would insert two elements before the list element with CSS id "idPeace": $("#idPeace").before("<li>Peter W. Higgs</li>", "<li>Francois Englert</li>")

The .after() method has another variant: .insertAfter(). These two methods differ primarily in terms of syntax. With .after() method, if we have node.after(x), then the element x is inserted after the node. But with .insertAfter() method, we can do it as x.insertAfter(node) -- this also means that we need to insert element identified by x or a list of elements identified by x and they all should be inserted after the node element. In simpler words, with .after(), we start with the element where we want to insert and the node that we want to insert. With .insertAfter(), we start with the node that we want to insert followed by the element where we want to insert.

Thus, with respect to .after() method, the .insertAfter() simply flips the order of elements. Hence, $("<li>Peter W. Higgs</li>").insertAfter($("#idPeace")) would insert a new list element after the list element with CSS id "idPeace" and is equivalent to $("#idPeace").after("<li>Peter W. Higgs</li>").

Like the case of .after() and .insertAfter(), we also have .insertBefore() along with the .before() method. So, if we want to insert one list node before the "idPeace" element, then we can do that as $("<li>Peter W. Higgs</li>").insertBefore($("#idPeace")). Likewise, if we want to insert a list node before all the elements with the "twoTimesWinner" CSS class, then we can do that as $("<li>Peter W. Higgs</li>").insertBefore($(".twoTimesWinner")).

Both .after() and .before() methods also accept a function. For inserting new nodes, this function should return these new nodes.

The .replaceWith(x) method replaces the element invoking this method with the new content x. In addition, this method also returns the deleted element. Like the case of .after()/.insertAfter() and .before()/.insertBefore() pairs, the .replaceAll() is similar to .replaceWith() but with the ordering reversed. Thus, elem.replaceWith(x) is same as x.replaceAll(elem) since in both cases, we replace the element elem with the new content x.

The next two methods, .detach(x) and .remove(x), remove the DOM element x from the element that invokes these methods. One key difference, however, is that the .detach(x) method retains all data and event-related information about the element. If needed, we can reattach it later. However, the .remove(x) method deletes both data and event-related information about the element x. Along the similar lines is the .empty() method that removes all the child nodes of the element that is invoking it along with their data and event information.

Now that we are done with the introduction of above methods, let us write some examples that implement these methods.

Our first example looks at the .after() method, .insertAfter() method, and .after() method with a function.

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <div>Nobel Laureates:</div>
 <ol>
     <li id="idPeace">Mother Teresa</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {
     var arr = ["Michael Levitt", "Arieh Warshel", "Martin Karplus"];

     // The regular .after() variant.
     $("#idPeace").after("<li>Peter W. Higgs</li>");

     // The .insertAfter() variant.
     $("<li> Alice Munro </li>").insertAfter($("#idPeace"));

     // The .after() variant with the function.
     $("li").after(function (indx) {
         return "<li id=id" + indx + ">"+ arr[indx] + "</li>";
     });
 });
 </script>
 </body>
 </html>

If we were to view the source, we would find that the new elements appear as follows. The nodes with values "Alice Munro" and "Peter W. Higgs" are added after the element with CSS id "idPeace". Next, the example calls the .after() variant with function and uses $("li") as the elements. With each function call, it passes the value present in the arr and hence, these elements are added after each of the existing list element. We can identify these new elements using the "id*" format.

Please note that when we select the View Source of the page (basically, right click on the page and select the option to view source), it would not show the newly added elements since View Source shows only the initial HTML content. There are several ways around this. One option is to select all the list elements on the page and then right click. With right click, we would see an option of viewing selection source. Yet another way is to use debugging tools for browsers -- for example, using Firebug in Firebox.

 <li id="idPeace">Mother Teresa</li>
 <li id="id0">Michael Levitt</li>
 <li> Alice Munro </li>
 <li id="id1">Arieh Warshel</li>
 <li>Peter W. Higgs</li>
 <li id="id2">Martin Karplus</li>

Here is the actual page:



Figure: Manipulating DOM using jQuery's after-related Methods

Using the before-based methods is analogous to the above example, except that the new nodes would be added before the element with CSS id "idPeace". In other words, this starting list element would remain the last element if we use the before-based methods. Here is the earlier example rewritten using the before-based methods:

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

 <body>
 <div>Nobel Laureates:</div>
 <ol>
     <li id="idPeace">Mother Teresa</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {
     var arr = ["Michael Levitt", "Arieh Warshel", "Martin Karplus"];

     // The regular .before() variant.
     $("#idPeace").before("<li>Peter W. Higgs</li>");

     // The .insertBefore() variant.
     $("<li> Alice Munro </li>").insertBefore($("#idPeace"));

     // The .before() variant with the function.
     $("li").before(function (indx) {
         return "<li id=id" + indx + ">"+ arr[indx] + "</li>";
     });
 });
 </script>
 </body>
 </html>

If we were to look at the list items, we would see the following output:



Figure: Manipulating DOM using jQuery's before-related Methods

The output confirms that since elements are being inserted using the before methods, the element with CSS id "idPeace" remains at the very end of the list. If we were to view the source, we would find that the new elements appear as follows. The nodes with values "Alice Munro" and "Peter W. Higgs" are added before the element with CSS id "idPeace". Next, the example calls the .before() variant with function and uses $("li") as the elements. With each function call, it passes the value present in the arr and hence, these elements are added before each of the existing list element.

Our third example focuses on the two replace methods: .replaceWith() and .replaceAll(). As stated earlier, one of the main differences between the two methods is that the order of elements is reversed.

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

 <body>
 <div>Nobel Laureates:</div>
 <ol>
     <li id="idPhys" class="twoTimesWinner">Marie Curie</li>
     <li id="idChem" class="twoTimesWinner">Marie Curie</li>
     <li id="idPeace">Mother Teresa</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {

     $("#idPhys").replaceWith("<li>Peter W. Higgs</li>");
     $("<li>Francois Englert</li>").replaceAll($("#idChem"));

 });
 </script>
 </body>
 </html>

If we look at the updated source, once the page loads, we would see different elements present in the list. This is because, we have replaced the two elements with CSS ids, "idPhys" and "idChem" with newer elements.



Figure: Manipulating DOM using jQuery's replace-related Methods

Our last example takes a look at the delete methods; the example is provided below. This example uses .remove() and .detach() methods to get rid of two of the elements. Next, it calls the heavy-weight, .empty() method on the ordered list to delete all of its child elements. Note that, if we are going to call the .empty() method on the ordered list, there is really no need to call .remove() and .detach() methods on elements of the ordered list -- we do that just for the sake of demonstration. If we were to load this page, then we would see that the ordered element has no child list elements. Hence, we omit the output.

 <!doctype html>
 <html>
 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
 </script>

 <body>
 <div>Nobel Laureates:</div>
 <ol id="idOl">
     <li id="idPhys" class="twoTimesWinner">Marie Curie</li>
     <li id="idChem" class="twoTimesWinner">Marie Curie</li>
     <li id="idPeace">Mother Teresa</li>
     <li id="idPhys2013A">Peter W. Higgs</li>
     <li id="idPhys2013B">Francois Englert</li>
 </ol>

 <script type="text/javascript">
 $(document).ready(function() {
     $("#idPhys").remove();
     $("#idChem").detach();
     $("#idOl").empty();
 });
 </script>
 </body>
 </html>




comments powered by Disqus