I need to set random data-id with two value A y B. I need a script that can do this
<div data-id="A" />
....
</div>
CodePudding user response:
For archiving this think you have to do three steps.
First: Collect all values you need into an array.
var myPossibleValues = ["A","B"];
Second: Generating a random integer number.
Based on Generate random number between two numbers in JavaScript
var randNum = Math.round(Math.random() * myPossibleValues.length);
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.
var videoDiv = document.getElementsByClassName("demo");
videoDiv[0].setAttribute("data-id",myPossibleValues[randNum]);
Due to the fact that getElementsByClassName()
returns an array, the [0]
is nessecary for the -only- first matched html element.
CodePudding user response:
This answer is a good solution but since the Issue only needs to select a value from two possibilities I would not overcomplicate things.
const demo = document.querySelector('.demo');
demo.setAttribute('data-id', Math.random() > 0.5 ? 'A' : 'B');
What this script does:
- get one element that matches the selector
.demo
- set the attribute
data-id
to either A or B depending on if the random value is above 0.5 or below - the chances are 50/50