treasureireland
treasureireland

Reputation: 87

Setting a JS variable and using it in html tag

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?

Upvotes: 5

Views: 30915

Answers (2)

Viren Rajput
Viren Rajput

Reputation: 5746

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

Upvotes: 2

Ruan Mendes
Ruan Mendes

Reputation: 92324

Use

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

You can't open a script tag inside an attribute

Upvotes: 8

Related Questions