Uncategorized

Lesson 6 – DOM Manipulation

jQuery makes it extremely easy and efficient to manipulate DOM in multiple ways. You no longer need to write lines and lines of code to select an element or modify its attributes. You can simply use methods in the likes of .val(), .html(), .attr(), and many more to retrieve information from an html document. Subsequently, you can use this information for different purposes later on.

For example, the replaceWith() method enables you to replace a complete element or elements within DOM. Here is the syntax.

 selector.replaceWith( content )

The first part of the code is the element you want to replace. Then you will put whatever you want to replace the element with in the parentheses.

We are going to replace the division element in the following example with an h1 element.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM Manipulation</title>
    [block]0[/block]

    
      $(document).ready(function() {
           $('div').click(function () {
              $(this).replaceWith("

jQuery is very popular

"); }); }); <style> .replace { color: #fff; background-color: #000; margin: 12px; padding: 12px; border: 1px solid grey; width: 140px; } </style> </head> <body>
Click on this square
</body> </html>

You will get the following output when you execute this code.

However, the h1 element will replace the black box when you click on it. This is a classic case of DOM manipulation in jQuery.

Another popular method in jQuery is html(). This particular method fetches all the html contents of all the matched elements. Let’s understand the concept with an example.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM Manipulation</title>
    [block]1[/block]

    
       $(document).ready(function() {
            $('.replace').click(function () {
               var add = $(this).html();
               $('.result').text(add);
            });
         });
     

     <style>
        .replace {
           color: #fff;
           background-color: #000;
           margin: 12px;
           padding: 12px;
           border: 1px solid grey;
           width: 140px;
        }
     </style>
</head>
<body>
      <p class="result"></p>
      
We have a black square
</body> </html>

You will once again get a black box when the above code is initially executed. However, when you click on the box, the browser will add its content to the paragraph element.

In the next lesson, we are going to study events in jQuery.