How to get the text without HTML element using JavaScript ?

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
- Using textContent property
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>     <divclass="main">         Welcome to zambiatek     </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>     <divclass="main">         Welcome to zambiatek     </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 | 
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
 
				 
					


