Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the difference between text() and html() in jQuery?
jQuery comes with a lot of methods to manipulate DOM elements. Among these methods are text() and html(), which are commonly used but serve different purposes ?
- text() ? This method sets or returns only the text content of elements selected, ignoring any HTML tags.
- html() ? This method sets or returns the complete HTML content of elements selected, including all HTML tags.
Key Differences
The main difference between these methods lies in how they handle HTML markup ?
-
text()treats HTML tags as plain text and will display them literally -
html()interprets HTML tags and renders them as actual markup
Example
You can try to run the following code to learn how to manipulate content with text() and html() methods ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
alert("Using text()- " + $("#demo").text());
});
$("#button2").click(function(){
alert("Using html()- " + $("#demo").html());
});
});
</script>
</head>
<body>
<p id="demo">This is <b>demo</b> text.</p>
<button id="button1">Text</button>
<button id="button2">HTML</button>
</body>
</html>
The output of the above code is ?
When you click "Text" button: "This is demo text." When you click "HTML" button: "This is <b>demo</b> text."
Conclusion
Use text() when you need to work with plain text content only, and html() when you need to include or preserve HTML markup within your elements.
Advertisements
