0

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?

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

OP states: I know I can go through the array afterwards and strip out any empty values... save having that extra step - I don't think OP realises how simple .filter(t=>t) is.
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.