Skip to content
Related Articles

Related Articles

How to get the text without HTML element using JavaScript ?
  • Last Updated : 27 Apr, 2020

Given an HTML document containing some elements and the task is to get the text inside an HTML element using JavaScript. There are two methods to get the text without HTML element which are listed below:

  1. Using innerText property
  2. Using textContent property

Using innerText property: We can use innerText property to get the text from HTML element.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
  
<head
    <title
        Get the text inside HTML
        element using JavaScript
    </title
</head>
  
<body>
    <div class="main">
        Welcome to GeeksforGeeks
    </div>
  
    <script>
        const div = document.querySelector('.main');
  
        alert(div.innerText);
    </script>
</body>
  
</html>

chevron_right


Output:

Using textContent property: We can also use textContent property to get the text from HTML element.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html
  
<head
    <title
        Get the text inside HTML
        element using JavaScript
    </title
</head>
  
<body>
    <div class="main">
        Welcome to GeeksforGeeks
    </div>
   
    <script>
        const div = document.querySelector('.main');
   
        alert(div.textContent);
    </script>
</body>
  
</html>

chevron_right


Output:

Difference between innerText and textContent:

  1. The innerText property returns only human-readable text while the textContent property returns all the text including <script> and <style> tag.
  2. The innerText property take care of styling of elements and did not return any hidden elements while textContent property returns all the elements including the hidden ones.
  3. The innerText property is defined only for HTMLElement objects, whereas textContent property is defined for all Node objects.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :