1

I have multiple buttons and inputs. I am trying to push innerText to array. Since there are different types of tags I need to specify 'if' to pick either the value for inputs or innerText of buttons.

This is what I have so far:

if ($("#dragulaContainer2").children().length > 0) {
  var arraySelected = [];
  var children = $('#dragulaContainer2').children();

  for (var i = 0; i < children.length; i++) {
    arraySelected.push(children[i].innerText);
  }
  console.log(arraySelected);
}

My non-coding logic behind it would be:

If childrens inner Text equals "" than take value instead.

But how to build the code? And add it to innerText line as if statement?

Added this but it is not working....

if ($("#dragulaContainer2").children().length > 0) {
  var arraySelected = [];
  var children = $('#dragulaContainer2').children();

  for (var i = 0; i < children.length; i++) {

    arraySelected.push(children[i].(if (innerText === "") {
      val
    } else {
      innerText
  });
}
console.log(arraySelected);
}
3
  • 1
    Yes, you'd do exactly as you described in your question. Have you done that yet? Commented Feb 26, 2018 at 16:03
  • Dont have any idea how to write it... Does it go before for loop? Does it go inside? Commented Feb 26, 2018 at 16:03
  • There should be a children[i].tagName you can reference. Commented Feb 26, 2018 at 16:04

1 Answer 1

3

So, if no text, push the value instead

var arraySelected = $("#dragulaContainer2").find(":input").map(function() {
  return this.textContent || this.value;
}).get();

console.log( arraySelected );
<div id="dragulaContainer2">
  <input value="0">
  <input value="test 1">
  <span>test 2</span>
  <textarea>test 3</textarea>
  <p>test 4</p>
  <button>btn text</button>
  <button value="btn val">use text</button>
  <button value="use value"></button>
</div>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

or if you use ES6 you can "shorten" to

$("#dragulaContainer2").find(":input").map((i,el) => el.textContent || el.value).get();

Using your if else style of coding, it would look like:

var $inp = $("#dragulaContainer2").find(":input");
var arraySelected = [];

$inp.each(function(){
    if(this.textContent) {
      arraySelected.push(this.textContent);
    } else {
      arraySelected.push(this.value);
    }
});  

console.log( arraySelected );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, what would it look like if I wanted to continue with my if else?

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.