How To Get The Text Of A Div Element Using JavaScript

How To Get The Text Of A Div Element Using JavaScript

When working with Javascript, it is very common to get the content inside an HTML tag, and sometimes you also need to assign content to HTML tags to create messages for users. Here are some ways to help you get the text of a Div element using Javascript.

Get the text of a Div element using Javascript.

Using getElementById with innerText, innerHTML or textContent

GetElementById in Javascript is a method of DOM object, which works to get an element from the DOM through the value of that element’s id attribute.

The syntax to use the getElementById method in Javascript is as follows:

document.getElementById(id)

Parameters

  • id: is the value of the element’s id attribute to get.

The getElementById method will return the Element Object if an element with the specified id is found and will return null if no matching element is found.

Code HTML sample

<div id="id1">
     Hello guys, <span style="display: none;"> welcome to LearnshareIT</span>
</div>

To get the text inside a Div element using Javascript, we can use one of the following syntaxes.

let text = document.getElementById("id1");

// get the html content inside a Div element
console.log(text.innerHTML);

// get the text content inside an Div element
console.log(text.textContent);

// get the text inside a Div element
console.log(text.innerText);

Output

Hello guys, <span style="display: none;"> welcome to LearnshareIT</span>
Hello guys,  welcome to LearnshareIT
Hello guys,

Difference between innerText, innerHTML, textContent in Javascript

As the results of the above example, different methods give different results. So the difference between innerText, innerHTML, textContent is:

  • innerHTML: will print out the text and the tags in this div.
  • textContent: will print the text content and the content of the tags inside this div. It gives you everything, both visible and hidden.
  • innerText: will print out the text content, trim spaces between lines, and add line breaks between items. 

In the above example, innerText is not displaying the content of the hidden tag (because the span has display: none, this is used to hide this span tag).

Summary

Above, I showed you how to get the text of a Div element using Javascript by the getElementById property and innerText, innerHTML, or textContent. I hope they are helpful to you. To better understand the lesson’s content, practice rewriting today’s examples. And let’s learn more about Javascript in the next lessons here. Have a great day!

Maybe you are interested:

Leave a Reply

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