jQuery html

The jquery html() method is used to set or get the HTML content of an element in the HTML document.

In this tutorial, you will learn about jQuery html() method, its syntax and usage, with examples.

Syntax jQuery html

Following is the syntax to use jQuery html() method

Get HTML content

To get the HTML content of an Element in the HTML document,

var x = $("htmlElement").html();

Set HTML content

To set or modify HTML content of an Element in the HTML document,

$("htmlElement").html("modified html content.");

Examples jQuery html

The following examples help you understand the usage of jQuery html() method.

1 Example Get HTML value of an HTML Element

In the following jQuery html() example, there is a button and paragraph. When the button is clicked, we shall get the HTML text of paragraph, referenced by id in the javascript, and display it through an alert.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    alert($("#pid").html());
  });
});
</script>
</head>
<body>

<p id="pid">Original HTML.</p>

<button id="btn1">Set HTML</button>

</body>
</html>

2 Example Set HTML value of an HTML Element

In the following jQuery html() example, there is a button and paragraph. When the button is clicked, we shall use html() method to set different HTML content for the paragraph element. In the example, elements are selected using their ids.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("#pid").html("<b>Modified HTML through jQuery.</b>");
  });
});
</script>
</head>
<body>

<p id="pid">Original HTML.</p>

<button id="btn1">Set HTML</button>

</body>
</html>

Conclusion

In this jQuery Tutorial, we have learnt jQuery html() method : Syntax and Usage with examples.