I’m starting slowly to apply JavaScript to my project and I’ve used the getElementById method in some of them and it always works without this .innerHTML. I’ve seen it today in one of the tutorials and I’ m not sure if I should add it to my code? I’m a bit confused.
If you have the id=“demo” in a p tag for example then this code
will allow you to see the Hello World text in that p tag.
Here is a codepen example showing the difference between using innerHTML and leaving it off completely. In the demo2 example, you will notice the Hello World does not display on the screen and there is an error.
So the getElementById or other javascript selectors returns an element in the DOM, right? And that element has some built-in methods and properties. They’re a built-in part of the DOM manipulation interface we get with javascript in the browser.
HTMLElement.innerHTML is one of those properties. We can read it to see, in a string, what the html contained inside that element looks like, or we can set it equal to a string, changing the html within that element as we like.
HTMLElement.innerText and HTMLElement.textContent do much the same, except that they show the displayed text content (minus any html tags) or allow us to write text directly into the element.