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

155
Views
Vanilla JS window.location by attribute by classname

I am trying to go from a Bootstrap 4 framework to a Bootstrap 5 framework - which means moving away from jQuery.

I have several elements on a page all with the classname .info-box and an attribute as follows

<div class="card card-icon col-md-4 info-box" data-href="file.php?e=AA">
<div class="card card-icon col-md-4 info-box" data-href="file.php?e=BB">
<div class="card card-icon col-md-4 info-box" data-href="file.php?e=CC">

When the user clicks on the card element, the intent is to open the link. The following JS gets close, but it links all three card elements to the Last Link (=CC)

        var elements = document.getElementsByClassName('info-box');
        for(var i = 0; i < elements.length; i++) {
            var element = elements[i];
            var newLoc= elements[i].getAttribute('data-href');
            element.onclick = function() {window.location = newLoc;}
        }

Can you suggest a way to make the correct data-href attribute link to the correct card?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

I think I found a solution .. Does this seem efficient?

<script>
    var elements = document.getElementsByClassName('info-box');
    [].forEach.call(elements, function(elements) {
      elements.onclick = function() {
        var newLoc= this.getAttribute('data-href');
        window.location = newLoc;
      }
    })
</script>

Found it over here .. javascript: call function by classname

about 4 years ago · Juan Pablo Isaza Report

0

var elements = document.getElementsByClassName('info-box');
    for(let i = 0; i < elements.length; i++) {
        let element = elements[i];
        let newLoc= elements[i].getAttribute('data-href');
        element.onclick = function() {window.location = newLoc;}
    }

Use let instead of var.

about 4 years ago · Juan Pablo Isaza Report

0

The problem is that var does not have block scope, which means in your case the variable newLocis defined globally. Use let instead of var.

I think I found a solution .. Does this seem efficient?

Your solution should also work fine, because it wraps the var newLoc in a function, which limits its scope. Using let is generally good practise though.

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!