'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?



Solution 1:[1]

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);

Solution 2:[2]

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>

Solution 3:[3]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jkoch
Solution 2 nonameyet
Solution 3