Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
treasureireland Avatar asked Dec 10 '12 18:12

treasureireland


People also ask

Can we use JavaScript variable in HTML attribute?

Use getElementById to show JavaScript variable in HTML attribute. This method will show variable value into particular HTML element.

How do you assign a variable in HTML?

As above, to declare a variable, use the var keyword followed by the variable name, like this: var surname; var age; Notice those semicolons (“;”)? Almost every line in JavaScript ends in a semicolon - you'll be using them a lot.

How do you assign a block of HTML to a JavaScript variable?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.

Can you do variables in HTML?

The <var> element in HTML defines a text as a variable and can be used to define variables of a mathematical expression or variables of a piece of code. The text enclosed in the <var> element is normally displayed in italics. Note: The <var> element supports all global attributes and event attributes.


1 Answers

Use

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

You can't open a script tag inside an attribute

like image 71
Juan Mendes Avatar answered Sep 28 '22 17:09

Juan Mendes