0

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.

Alex
  • 1,064
  • 1
  • 11
  • 16

2 Answers2

1
<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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Thank you, yes I agree and I have heeded your advice to change to event handlers in the script tags. (Named a class that closes the parent div). However, I am still glad that I know this so I don't make this mistake again! – Alex Jan 05 '17 at 23:21
0
<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>
jbolanos
  • 615
  • 3
  • 9
  • 20
  • Thank you, I appreciate the help. However, as I mentioned these divs are being created dynamically. I will not know the name of the div so hard coding the id like this will not work. Also getting it to work was not the issue, as mentioned I got it to work, I wanted to know my my method did /not/ work. – Alex Jan 05 '17 at 23:31
  • Then turn it into a function and pass the value as a variable – jbolanos Jan 05 '17 at 23:40