Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!