Search code examples
javascripthtmlgetelementbyid

inserting html into getElementById("id").innerHTML


I changing HTML near the top of my website using JS and its not working I was having a similar problem earlier because the quotations were messing it up but i tried to fix it with that method but it still isn't working.

document.getElementById("accTabs").innerHTML = "<a onclick="document.getElementById('id01').style.display='block'" class="w3-bar-item w3-button" id="log"><i class="fas fa-users"></i> SIGN IN</a>";


Solution

  • document.getElementById("accTabs").innerHTML = "<a onclick=\"document.getElementById('id01').style.display='block'\" class=\"w3-bar-item w3-button\" id=\"log\"><i class=\"fas fa-users\"></i> SIGN IN</a>";
    <div id="accTabs"></div>

    Please try like this snippet. Your error is raised because you used quote incorrectly.

    document.getElementById("accTabs").innerHTML = "<a onclick="alert('ok')"></a>";
    

    If you try like this code, then double quote inside double quote will cause the problem. You need to change this like below to escape the problem

    document.getElementById("accTbs").innerHTML = "<a onclick=\"alert('ok')\"></a>";
    

    You could also use ES6 template literal. then you can use double quote and single quote inside string without any problem.

    document.getElementById("accTabs").innerHTML = `<a onclick="alert('ok')"></a>`;