jQuery Introduction | Manipulating Elements | Changing Element Content .html() .text()
Changing the Inside of Existing Elements
The following methods let you return or set new elements or content inside existing elements.
| Method | Description |
|---|---|
| .html() | Returns or sets the HTML content of the element. |
| .text() | Returns or sets the text content of the element. |
.html() Method
The .html() method changes the content of the selected element to a new HTML element.
When an HTML element exists as follows:
<p>Hello.</p>
Using the .html() method, you can change the content of the <p> element to a new HTML element.
$("p").html("<div class='wrap'>This is devkuma.</div>");
.text() Method
The .text() method changes the content of the selected element to plain text.
When an HTML element exists as follows:
<p>Hello.</p>
Using the .text() method, you can change the content of the <p> element to new text.
$("p").text("This is devkuma.");
Difference Between .html() and .text()
If the content of the selected element includes HTML tag elements, .html() applies and displays those tags, while .text() displays the sentence as-is without applying HTML tags.
When an HTML element exists as follows:
<p>Hello.</p>
If a sentence containing HTML is displayed as below, the HTML tags are not applied and the sentence is displayed as-is.
$("p").text("<div class='wrap'>This is devkuma.</div>");
.html() Application Example
This example uses .html() and setInterval() to display the current time.
When it runs, the time display changes every second, or every 1000 ms.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>Current Time</title>
<script>
$(function() {
$("#now").text(new Date());
setInterval(function() {
$("#now").text(new Date());
}, 1000);
});
</script>
</head>
<body>
<h1>Current Time</h1>
<div id="now"></div>
</body>
</html>