Skip to content
Advertisement

How can I change data-id value in Class with a script?

I need to set random data-id with two value A y B. I need a script that can do this

<div class="demo" data-id="A" />
....
</div>

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement