Setting a JS variable and using it in html tag

30,728

Solution 1

Use

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

You can't open a script tag inside an attribute

Solution 2

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

Share:
30,728
treasureireland
Author by

treasureireland

Updated on December 12, 2020

Comments

  • treasureireland
    treasureireland over 3 years

    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?