The DOM: The innerHTML Property

Hi guys,

Can someone please help me understand why we have to add .innerHTML property to the below method?

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

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.

Sorry if that’s a silly question.

Thank you!

Hi @AnnaxT !

The innerHTML inserts the html into the document.

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.
Screen Shot 2021-07-29 at 4.08.26 PM

2 Likes

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.

To learn more, visit https://devdocs.io and search for innerHTML.

2 Likes

Thank you ! So if I want to see/edit the content inside of an element I need to use .innerHTML property? Do I understand that correctly?

I wrote the below function today and it works just perfect without it that’s why I was confused.

let overlay = document.getElementById("overlay");

function showOverlay() {
    overlay.style.zIndex = 0;
    overlay.style.opacity = 0.5;
}

If you want to display some text on the screen then you would use innerHTML or text content.

But in the code you are showing me, it doesn’t look you want to display any text.

2 Likes

Thank you @jwilkins.oboe, now I understand what it’s used for.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.