Skip to content Skip to sidebar Skip to footer

Does This Not Work Because I Can't Use A Script In A Div?

I am making a website with a program editor, for users to make HTML programs. I usually test this out by inputting into the body input

Solution 1:

The asked question is do scripts work in div's. Yes <script></script> tag content executes inline where it appears in the document.

However, it always executes in the document context. Meaning this === document. So to bind to the div's onclick method (the way you handle ui events in javascript) you need to find the div :

document.findElementById("my-div-id").onclick = function(e) {
   // do something
};

Note this clobbers the default behavior for the element if there is a default click behavior (like on an a tag)

Also to be more clear on the expected behavior. Do this

<script>functiondoSomething() {
        alert();
    }
</script><buttononclick="doSomething()">Button</button>

Post a Comment for "Does This Not Work Because I Can't Use A Script In A Div?"