Home »
jQuery »
jQuery DOM Manipulation Methods
jQuery html() Method
jQuery | html() Method: Learn about the jQuery html() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on September 26, 2022
html() Method
First, let's discuss what we mean by HTML. The HTML here can be said to the content, images, videos, etc. that we see on the webpage. Therefore, the html() method helps to get or set the HTML content using jQuery. This is a very simple method through which we can return the HTML content of a particular element, also we can set some new content through this. As it returns the HTML content, hence by this we mean that it returns the text along with other present tags in that element.
html() Method Syntax
$(selector).html();
$(selector).html(content);
By using only html(), we will be returned the HTML content of the selector. But when the content is specified within, then the selector's content is either created or replaced by the provided content.
The below examples illustrate the implementation of the html() method in detail. When the button provided is clicked, then in Example 1, it returns the content in the console. Whereas in Example 2 it replaces the old content with the new one provided.
jQuery html() Method Example 1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>jQuery - Html</h2>
<p>Click the following button to get the div content in the console.</p>
<button>Click Here</button>
<hr>
<div>Welcome to <b>Include Help</b> !!!</div>
<hr>
</body>
<script type="text/javascript">
// Method 1
$(document).ready(function() {
$('button').click(function() {
var content = $('div').html();
console.log(content);
})
});
</script>
</html>
Output:
jQuery html() Method Example 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>jQuery - Html</h2>
<p>Click the following button to get the div content in the console.</p>
<button>Click Here</button>
<hr>
<div>Welcome to Include Help !!!</div>
<hr>
</body>
<script type="text/javascript">
// Method 2
$(document).ready(function() {
$('button').click(function() {
$('div').html('Thanks for visiting Include Help !!!');
})
});
</script>
</html>
Output:
After clicking on "Click Here" Button