0

I have this:

$(".section").each( function() {
    var x = $(this).attr('data-test');
    var y =[];
    y.push(x);
});

I will get 10 values for data-test, and I want to push them to the array 'y' to be like this:

['1','2','3','4','5','6'...'10']

How do I "split up" x into each of its values and push them to y?

EDIT:

HTML e.g:

<li class="section" data-test="15"></li>
<li class="section" data-test="6"></li>
<li class="section" data-test="78"></li>

and so on

1
  • @RoryMcCrossan x will contain 10 values as it's checking each 'data-test' for each section. At the moment when I console log y, I get 10 separate arrays with one value in each. Commented Dec 2, 2015 at 16:28

3 Answers 3

7

Given your HTML sample you can use map() to create the array for you:

var y = $(".section").map(function() {
    return $(this).data('test');
}).get();

// This is only for display purposes
$('div').text(JSON.stringify(y)); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="section" data-test="15">15</li>
  <li class="section" data-test="6">6</li>
  <li class="section" data-test="78">78</li>
</ul>

<div></div>

Sign up to request clarification or add additional context in comments.

1 Comment

There was another answer posted which I tried, and it worked, so I upvoted yours rather than selected as the correct answer, thanks.
2

Obligatory vanilla answer using ES6

var y = [];
Array.from(document.querySelectorAll(".section")).forEach(x => {
    y.push(x.getAttribute("data-test"))
});

The issue you're running into is you're resetting the array y upon each iteration, thus removing previous indexes.

Array.from() converts the NodeList returned from querySelectorAll into a nicer iterable, (you can also use map instead of forEach) then simply push the data attribute of x into the array

Comments

0

$.merge() could be used to concatenate items to an array

var y = [];

$(".section").each(function() {
  $.merge(y, [$(this).data("test")])
});

console.log(y)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="section" data-test="15"></li>
<li class="section" data-test="6"></li>
<li class="section" data-test="78"></li>

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.