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

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Comments are closed, but trackbacks and pingbacks are open.