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

119
Visualizações
jQuery add element to array if exists and is not empty

I am adding elements to an array like this..

myarray = [];
myarray.push($('#name1').text());
myarray.push($('#name2').text());
myarray.push($('#name3').text());
myarray.push($('#name4').text());

This is working correctly, but i am trying to only push to the array if the element exists and has content.

I know I can go through the array afterwards and strip out any empty values but is there a way I can do it first to save having that extra step?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

If it's about the codes length there are shorter ways to write this.

const myarray = ['#name1','#name2','#name3','#name4']
    .map(n => $(n).text()).filter(t=>t);
about 4 years ago · Juan Pablo Isaza Relatório

0

If you have any other indicator than the mentioned code, you could use them to dynamically check the element name, other wise you could use simple if else to check if it's exist.

myarray = [];
// example iteration of 4 id
id = 4;
for (let i = 1; i <= id; i++) {
  if ($(`#name${i}`).text()) {
    myarray.push($(`#name${i}`).text())
    console.log('exist')
  } else {
    console.log('not exist')
  }
}
console.log(myarray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="name1"></div>
<div id="name2">hey</div>
<div id="name3">no</div>
<div id="name4"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Use each() function.

myarray = [];
$("span").each(function(){
  if ($(this).text().trim().length > 0) {
    myarray.push($(this).text());
  }
});
console.log(myarray);

Example html:

<span id="name1">Hello</span>
<span id="name2"></span>
<!-- span#name3 skipped -->
<span id="name4">World</span>
about 4 years ago · Juan Pablo Isaza 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