how to get text of element in jQuery?

To get the text value of element, you can:

use .text()

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
  <script src="jquery.min.js"></script>
  </head>
  <body>
  <div>aa<b>bb</b></div>
  <div>cc</div>
    <script>
    alert($("div").text());
    </script>
  </body>
</html>

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.

reference:https://www.w3schools.com/jquery/jquery_dom_get.asp

Comments are closed, but trackbacks and pingbacks are open.