Reputation: 1094
I am creating a dynamic box that can close in a web page and am changing the html if a div with an 'onclick' function. However, when I use DOM to change the code, the string I am changing it to seems to magically alter and gets inputted incorrectly, thus making it not work.
I have simplified some code to show what I mean.
<head>
</head>
<body>
<div id="test"></div>
<script>
document.getElementById('test').innerHTML = '<a onclick="document.getElementById("MYdiv").remove()">Close</a>'
</script>
</body>
When I run this the MYdiv
changes to mydiv
and adds a space to the front. To fix the issue I changed the string "MYdiv"
to \'MYdiv\'
and everything seems to work well, but I want to know WHY the first method didn't work. If you know, or if I am missing something please let me know!
Thanks! PS currently testing on chrome.
Upvotes: 0
Views: 49
Reputation: 625
<div id="test"></div>
<div id="MYdiv">killme</div>
<script>
var link = document.createElement('a');
link.appendChild(document.createTextNode('close'));
link.onclick = function(ev){
ev.preventDefault();
document.getElementById('MYdiv').remove();
};
var el = document.getElementById('test');
el.appendChild(link);
</script>
Upvotes: 0
Reputation: 324820
<a onclick="document.getElementById("MYdiv").remove()">Close</a>
Spot the issue. Hint: colour coding.
Solution: fix your quotes or (better) don't use inline event handlers.
Upvotes: 1