I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, 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 a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?
I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, 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 a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?
Share Improve this question edited Dec 11, 2012 at 13:03 treasureireland asked Dec 10, 2012 at 18:08 treasureirelandtreasureireland 872 gold badges3 silver badges10 bronze badges 4- 3 What is this for? Why assign a random ID to an element? (Numeric-only IDs are invalid in HTML 4 btw) – Pekka Commented Dec 10, 2012 at 18:09
- 1 Just inject the div via javascript itself. Btw in html4 you shouldn't have leading numeric id's – aziz punjani Commented Dec 10, 2012 at 18:11
- And I'm not even sure you can put script tags inside attributes... – Ian Commented Dec 10, 2012 at 18:11
-
2
document.write
? In the end of 2012? – raina77ow Commented Dec 10, 2012 at 18:12
2 Answers
Reset to default 8Use
<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>
You can't open a script tag inside an attribute
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 the id
as the randomnumber
and append it to the body