Open In App

How to get the text without HTML element using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

Example: 

html




<!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>


Output: 

 

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

Example: 

html




<!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>


Output: 

Let us compare the properties of the two methods:

innerText textContent
It returns human-readable content It returns texts along with the tag
It returns only styling elements and not the hidden elements It returns all elements including hidden elements
It is defined only for HTMLElement objects It is defined for all Node objects


Last Updated : 07 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads