Bootstrap FreeKB - JavaScript - Getting Started with innerHTML replace
JavaScript - Getting Started with innerHTML replace

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 79972a in the box below so that we can be sure you are a human.