I need to set random data-id with two value A y B. I need a script that can do this
JavaScript
x
4
1
<div class="demo" data-id="A" />
2
.
3
</div>
4
Advertisement
Answer
For archiving this think you have to do three steps.
First: Collect all values you need into an array.
JavaScript
1
2
1
var myPossibleValues = ["A","B"];
2
Second: Generating a random integer number.
Based on Generate random number between two numbers in JavaScript
JavaScript
1
2
1
var randNum = Math.round(Math.random() * myPossibleValues.length);
2
The parameter myPossibleValues.length
allows you to exentd the array with additional elements and use it as maximum range value.
Third: Read the generated number, apply it on array and associate it to your data attribute.
JavaScript
1
3
1
var videoDiv = document.getElementsByClassName("demo");
2
videoDiv[0].setAttribute("data-id",myPossibleValues[randNum]);
3
Due to the fact that getElementsByClassName()
returns an array, the [0]
is nessecary for the -only- first matched html element.