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
How to get the value of div content using jQuery?
To get the value of div content in jQuery, use the text() method. The text() method gets the combined text contents of all matched elements. This method works for both XML and XHTML documents.
The text() method retrieves only the text content and ignores any HTML tags within the element. If you need to get the HTML content including tags, you can use the html() method instead.
Example
You can try to run the following code to get the value of div content using jQuery ?
<!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() {
var res = $('#demo').text();
alert("Text content: " + res);
});
$("#button2").click(function() {
var res = $('#demo').html();
alert("HTML content: " + res);
});
});
</script>
</head>
<body>
<div id="demo">This is <b>demo</b> text.</div>
<button id="button1">Get Text</button>
<button id="button2">Get HTML</button>
</body>
</html>
The output when clicking "Get Text" button will show ?
Text content: This is demo text.
The output when clicking "Get HTML" button will show ?
HTML content: This is <b>demo</b> text.
Conclusion
The jQuery text() method is the most common way to retrieve div content as plain text, while html() preserves the HTML formatting within the element.
