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

108
Views
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 answers
Answer question

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 Report

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 Report

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 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!