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

JavaScript

Advertisement

Answer

For archiving this think you have to do three steps.

First: Collect all values you need into an array.

JavaScript

Second: Generating a random integer number.

Based on Generate random number between two numbers in JavaScript

JavaScript

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

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