Setting JS variable and using it in html tag

I set the variable and I need to insert this variable into the html element, but I can not print it, this is the code:

<script> var randomnumber=Math.floor(Math.random()*11) </script> <div id="<script type="text/javascript">document.write(randomnumber)</script>"></div> 

Thanks.

Edit: I just used the div as an example, but I need to add a random number to the img tag, just like for the tracking tag, and it needs a unique identifier. Is there a better way to do this?

+4
source share
2 answers

Using

 <script> document.write('<div id="'+randomnumber+'" ></div>'); </script> 

You cannot open the script tag inside the attribute

+9
source

Or you can create it using JS :

 var randomnumber=Math.floor(Math.random()*11); a = document.createElement('div'); a.setAttribute('id',randomnumber); document.body.appendChild(a); // if you know the exact class or ID where it is to be appended you can use document.getElementsByClassName("myclass")[0].insertBefore(a, document.getElementsByClassName("beforeClass").firstChild); 

This will create a div with id as randomnumber and add it to body

+2
source

All Articles