Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda