< Jquery Tutorial

Jquery DOM Manipulation

← Previous Next →

JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division.

JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.


Content Manipulation

The html( ) method gets the html contents (innerHTML) of the first matched element.

Here is the syntax for the method −

selector.html( )

Example :

Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter −

The jQuery Example</title>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script> <script type = "text/javascript" language = "javascript">
$(document).ready(function() { $("div").click(function () { var content = $(this).html(); $("#result").text( content ); }); }); </script> <style>
#division{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>
Click on the square below:</p>
<span id = "result">
</span> <div id = "division" style = "background-color:blue;">
This is Blue Square!! </div> </body> </html>

DOM Element Replacement

You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well.

Here is the syntax for the method −

selector.replaceWith( content )

Here content is what you want to have instead of original element.

← Previous Next →