DOM Manipulation

To respond to user events, we wrote event handlers to modify HTML elements on the page.

jQuery comes with several useful methods to modify HTML elements. The next cards will cover a few common jQuery methods.

$( )

In jQuery, we often see $( ). It has two main uses:

  • To select existing HTML elements on the page.

$('p') selects all p elements on the page.

  • To create new HTML elements to add to the page.

$('<h1>') creates a new h1 element. The < > indicates that we want to create a new HTML element.

Jquery-function

Practice

Q:


.text()

The .text() method adds text to an HTML element.

Text

.appendTo()

$('.btn').click(function() {
  $('<li>').text('New item').appendTo('.items');
});
  • .prependTo()

    $('.btn').click(function() {
      $('<li>').text('New item').prependTo('.items');
    });
    
  • .remove()

    $('.btn').click(function() {
      $('.selected').remove();
    });
    
  • Practice

    Q:

    
    

    Six jQuery Methods

    $('.social li').click(function() {
      $(this).toggleClass('active');
    });
    
  • Try it out

    In the event handler below, add .addClass("read"); to $(this). This will add the CSS class "read" to the clicked item. Then click on the list items to see what this code does.

    
    

    Try it out

    In the event handler below, add .hide(); to $('.read'). The Hide button will remove selected items from the list.

    
    

    Try it out

    In the event handler below, add .toggle(); to $('.description'). This will alternate showing and hiding each item's description. Then click on the Toggle description button to see what this code does.

    
    

    Practice

    Q:

    
    

    Document Object Model

    jQuery also comes with methods that let us select HTML elements in relation to other elements.

    In the web page to the right, HTML elements are nested inside other elements, forming a hierarchy. This hierarchy can be visualized as a tree.

    This representation of HTML is called the Document Object Model (DOM).

    Dom

    DOM Traversal

    The DOM is useful to represent relationships between elements, similar to a family tree.

    For example, look at the ul element:

    • The two li elements nested inside are its child elements

    • The .article element is its parent element

    • the h2 and p elements are its sibling elements

    Here are three common jQuery methods that use these relationships to access and modify elements on the page.

    Traversal

    .next()

    The .next() method gets the next sibling of the selected element.

    Next

    .prev()

    The .prev() method gets the previous sibling of the selected element.

    Prev

    .children()

    The .children() method gets the children of the selected element.

    If provided a selector, the .children() method can get a specific child.

    Children

    Practice

    Q:

    
    
  • ?