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

258
Views
How to use JavaScript to set an attribute if a condition exists?

In the snippet below, I'm creating an array of all panels and all links within those panels.

Then, for each panel with the class of active, I want all the links to be set to tabindex="0". For all other links, I want tabindex="-1".

In my example, I don't understand why all links are set to tabindex="-1", when one of the panels has the active class. Why isn't it set to tabindex="0"?

const panels = document.querySelectorAll('.panel');
const links = document.querySelectorAll('.panel a');
panels.forEach(function(panel) {
  if (panel.classList.contains('active')) {
    Array.prototype.forEach.call(links, link => link.setAttribute('tabindex', '0'))
  } else {
    Array.prototype.forEach.call(links, link => link.setAttribute('tabindex', '-1'))
  }
})
<div class="panels">
  <div class="panel active">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>
  
  <div class="panel">
    <p>Hello <a href="#">World</a>. I am <a href="#">with</a> you.</p>
  </div>  
</div>

about 4 years ago · Juan Pablo Isaza
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!