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?
Use getElementById to show JavaScript variable in HTML attribute. This method will show variable value into particular HTML element.
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.
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.
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.
Use
<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>
You can't open a script tag inside an attribute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With