fightstarr20
fightstarr20

Reputation: 12598

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?

Upvotes: 0

Views: 450

Answers (3)

Shinjo
Shinjo

Reputation: 695

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>

Upvotes: 0

jkoch
jkoch

Reputation: 806

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

Upvotes: 2

user18473608
user18473608

Reputation:

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>

Upvotes: 0

Related Questions