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

189
Views
jQuery each() loop does not return control when a condition is met

I want return true/false from my function when the if condition is met. However it's not returning true, every time it returns false. Please help me. Thanks.

function catExists(cName) {
  $("#room_has_cat_table tbody tr td:first-child").each(function(index, item) {
    var existingCat = $(this).text();
    alert(existingCat);
    
    if (existingCat == cName) {
      return true;
    }
  });
  
  return false;
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The problem with your logic is because you cannot return a value from an anonymous function.

To correct your logic define a boolean variable which you can update inside the loop when a match is found:

function foo(cName) {
  let matchFound = false;

  $("#room_has_cat_table tbody tr td:first-child").each(function() {
    var existingCat = $(this).text();
    if (existingCat == cName) {
      matchFound = true;
      return; // exit the each() loop
    }
  });

  return matchFound;
}

However, a better approach entirely would be to use filter() to find the match. This avoids the need for the explicit loop:

let matchFound = $("#room_has_cat_table tbody tr td:first-child").filter((i, el) => el.innerText.trim() === cName).length !== 0;
about 4 years ago · Santiago Gelvez 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!