Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 76195

Unable to refactor inline script contained innerHTML in JavaScript

$
0
0

I currently have the following code in JavaScript:

container.innerHTML = `
            <h3 id="box-title"> Build Analysis
             </u><span id="close" class="close" 
            onclick=parentNode.parentNode.style.display='none';>x</span></h3>
             .... /* skipping the rest because it is irrelevant */

This is just code for dynamically inserting HTML content in the webpage (in this case box that can be opened and closed). My question is regarding in-line scripting. Currently it works with the onclick (which closes the window), but it uses inline scripting, which is not good.

I tried the solutions from this link:(the part with refactoring in-line scripting) https://csp.withgoogle.com/docs/adopting-csp.html

I tried the following solution from there, but nothing happens: In most cases the changes will be straightforward. To refactor event handlers, rewrite them to be added from a JavaScript block:

Copied from there:

<script> function doThings() { ... } </script>
<span onclick="doThings();">A thing.</span>

should become:

<span id="things">A thing.</span>

<script nonce="${nonce}">
document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('things')
          .addEventListener('click', function doThings() { ... });
});
</script>

However when applying it my project, it doesnt seem to work:

 ...
 </u><span id="close" class="close">x</span></h3>
...

<script>
                document.addEventListener('DOMContentLoaded', function () {
                document.getElementById('close')
                        .addEventListener('click', function closeBox() {
                            parentNode.parentNode.style.display='none';
                        });
                });
    </script>

I also tried putting a onclick=CloseBox() in the tag. It just doesn't register this functionality and nothing happens. Not even an error occurs. Can anyone please help? Thank you!


Viewing all articles
Browse latest Browse all 76195


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>