Search code examples
javascripthtmlinnerhtmlvargetelementbyid

Replacing <p></p> innerHTML with document.getElementById by using var


I'm trying to replace the id example that has <p> Hello! </p> with <p> Hi! </p> using var.

This is what I tried: var i = Hi!

document.getElementById('example').innerHTML = '<p>i</p>' but it changed example to <p>i</p>, not "Hi!"


Solution

  • You're looking for String concatenation. You originally surrounded the variable name with quotations, which causes it to be interpreted as a String.

    function go(){
        var i = "Hi!"
        document.getElementById('example').innerHTML = "<p>"+i+"</p>";
    }
    <div id="example"><p>Test</p></div>
    <button onclick="go()">Change</button>