how to get text of element in jQuery?

To get the text value of element, you can:

use .text()

<!DOCTYPE html>
    <meta charset=utf-8 />
  <script src="jquery.min.js"></script>

This displays “aabbcc”, i.e, .text() combines all the text of selected elements getting rid of html tags in them.

use .html()

If you replace .text() with .html() in the above example, it will display “aa<b>bb</b>”, i.e., .html() only gets the inner html of the fist element in the selected elements while keeping the html tags in it. This is the difference between .text() and .html(). If you read the post about getting text of selected element, you may get an illusion that jQuery() only contains one element or .text() only gets the first element’s content, which is definitely wrong. See the authority document of .text() and .html().

use .val()

.text() and .html() can also be used to get the text in <textarea>text</textarea>, but can not be used to get the text in <input value=”inputvalue”/>. To get the text in an <input> element, use .val() instead. And like .html(), .val() only returns the value of the first selected element. Note that we get and set the value of <input> using a function(method) .val() in jQuery, but we set and get the value using an attribute .value in javascript.


Comments are closed, but trackbacks and pingbacks are open.