jQuery DOM Manipulation

Introduction to DOM Manipulation

  • It provides different methods to manipulate DOM in an efficient manner.
  • There is no need to write lengthy code for modifying the value of the elements, attributes or extract the HTML code from a paragraph or division.
  • Methods like .attr(), .html() and .val() are provided by jQuery which act as getters, retrieve information from DOM elements for later use.

Content Manipulation

The html() method gets the inner contents of the first matched elements.

Syntax:
selector.html()

Example : Showing the use of .html() and .text(val) method

<html>
<head>
      <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
      </script>
      <script type="text/javascript" language ="javascript">
      $(document).ready(function()
     {
           $("div").click(function()
           {
                var content = $(this).html();
                $("#res").text(content);
           });
     });
     </script>
     <style>
           #d1
           {
                margin:20px;
                padding:24px;
                border:4px solid #666;
                width:80px;
           }
     </style>
</head>
<body>
        <p> Click on the square </p>
        <span id ="res"> </span>
        <div id = "d1" style = "background-color:green;"> Its a green color square!!! </div>
</body>
</html>


Output:

html text met1

When the square is clicked we get the following output:

html text met2

DOM Element Replacement

A complete DOM element can be replaced with the specified HTML or DOM elements.

Syntax:
selector.replaceWith(content)
Where,
         content – It is the replacement for the original element. It can be HTML or simple element.

Example : Demonstrating the replace With() method

<html>
<head>
      <script type = "text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
      </script>
      <script type="text/javascript" language ="javascript">
      $(document).ready(function()
      {
           $("div").click(function()
           {
                 $(this).replaceWith("<h4>JQuery is simple</h4>");
           });
      });
      </script>
      <style>
          #d1
          {
                margin:20px;
                padding:24px;
                border:4px solid #666;
                width:80px;
          }
          </style>
</head>
<body>
        <p> Click on the square </p>
        <span id ="res"> </span>
        <div id = "d1" style = "background-color:green;"> Its a green color square!!! </div>
</body>
</html>


Output:

html text met1
When you click on the square we get the following output
Click on the square
JQuery is simple