JavaScript

How to get the text of HTML element in Javascript

In this tutorial, we are going to see how to get the text of an HTML element in Javascript, for example <p>, <div>, <span>, etc. In the example below we will use the <div> tag as an example. There are two methods to get the text of an HTML element, either using the textContent or innerText property.
 

Method 1: Using the textContent property
<html>
   <body>
      <div id="myDiv">Welcom to StackHowTo!</div>
   </body>
   <script type="text/javascript">
      var text = document.getElementById('myDiv').textContent;
      alert(text);
   </script>
</html>

Output:

Welcom to StackHowTo!
 

Method 2: Using the innerText property
<html>
   <body>
      <div id="myDiv">Welcom to StackHowTo!</div>
   </body>
   <script type="text/javascript">
      var text = document.getElementById('myDiv').innerText;
      alert(text);
   </script>
</html>

Output:

Welcom to StackHowTo!
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *