-1

I have

<div id=test>
<div>

I am trying to insert script

var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.value = 'alert(1)';
document.getElementById('test').appendChild(s);

But after this i find only

<div id="test">
<script type="text/javascript">
</script>
</div>

Its not running alert(1)

How to do this?

2
  • 1
    You need to set the innerText, not the value. As if you had written the alert() inside the <script> tag yourself. Commented Mar 22, 2019 at 14:40
  • The issue is because you append the child to the div not the script. I think you may need to tell the script to run too. Wrap it in a self executing function or a function that you can then call. Oh - Jeremy has helped you out... Commented Mar 22, 2019 at 14:48

1 Answer 1

1

You want to use :

s.innerText = 'alert(1)';
Sign up to request clarification or add additional context in comments.

1 Comment

also can you tell me how to do it using jquery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.