Jquery Tutorial : Dom Manipulation

Resources » Bookshelf » Jquery Tutorial » Dom Manipulation

3. DOM And Attributes 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.

3.1. DOM Manipulation

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

3.2. Creating Elements

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 jQuery function:

    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]Note

    It is considered a best practice to put quotes around object property names because some words such as class are reserved keywords in JavaScript.

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

3.3. Inserting Elements

  • 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)

3.4. Inserting an Element Before or After Another Element

3.4.1. Before an Existing Element

  • .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>');

3.4.2. After an Existing Element

  • .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>');

3.5. Inserting an Element as the First or Last Child of a Parent

3.5.1. As the First Child

  • .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');

3.5.2. As the Last Child

  • .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');

3.6. Mass Insertion

  • 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>');

3.7. Moving Elements

  • 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 article so that it is the last child of the element whose id is section.

    • 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 section element.

      $('#section').append($('.article:first'));
    • In this example, the jQuery object returned is the article element.

      $('.article:first').appendTo($('#section'));
[Note]Note

If the target selection contains more than one element, the elements being moved are duplicated and inserted into each target.

3.8. Cloning (Copying) Elements

  • 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(); // 1
      $('#section').append($article); // 2

      1

      Here we do not get a reference to the jQuery selection object but a copy of the object.

      2

      Now we insert the copy of the elements; the original one has not moved.

3.9. Removing Elements

  • 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]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.

3.10. Replacing Elements

  • 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]Note

      .replaceWith() returns the original jQuery object (that is, the one just removed from the DOM).

    • The .replaceAll() method is corollary to replaceWith(), but with the source and target reversed.

      $('.menu-li1').each(function(){
        $('<h3>'+$(this).text()+'</h3>').replaceAll($(this));
      });

3.11. Element Content: HTML vs Text

  • 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]Note

Do not use the .text() method to get or set value for <input> elements. Use the .val() method instead

3.12. Other Element Attributes

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