JavaScript - Getting Started with innerHTML replace




by
Jeremy Canfield |
Updated: September 17 2024
| JavaScript articles
Here is an example of how you can create a variable that contains a DOM element using HTML and JavaScript querySelector.
<p class="demo">Hello World</p>
<script>
var foo = document.querySelector('.demo');
console.log(foo)
</script>
Navigating to the web page containing this markup should return something like this.

textContent can be used to return the content of the DOM element.
<p class="demo">Hello World</p>
<script>
var foo = document.querySelector('.demo');
console.log(foo)
var textContent = foo.textContent
console.log(textContent)
</script>
Which should return something like this.

And innerHTML replace can be used to replace values in the DOM element.
<p class="demo">Hello World</p>
<script>
var foo = document.querySelector('.demo');
foo.innerHTML = foo.textContent.replace("Hello", "Goodbye")
console.log(foo)
</script>
And now "Hello World" is "Goodbye World".

Did you find this article helpful?
If so, consider buying me a coffee over at