Using getElementById with innerText, innerHTML or textContent
The syntax to use the
- id: is the value of the element’s id attribute to get.
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>
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);
Hello guys, <span style="display: none;"> welcome to LearnshareIT</span> Hello guys, welcome to LearnshareIT Hello guys,
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).
getElementById property and
Maybe you are interested:
- Select elements by Multiple IDs using JS
Name of the university: HVNH BA
Major: htttql MIS