0

Im attempting to set this variable as a function, and set the variable's value to that function's output, but i just can't put my finger on how to grab the output correctly:

var prev = activeSection.prevAll();

var about = prev.each(function(){ 
     $(this).data('about');
})

Now the .data func's value is the value i want to set the about var to, however when i log the about var, i just get all the elements of the prev var, not the .data('about') of each of them, which i desire.

I know I'm off by something so minute... suggestions?

0

2 Answers 2

1

The jQuery .each function you are using just iterates over the elements. You're not adding them to a list, so nothing is happening with your value.

You would modify your existing code as follows to add your values to an array:

var prev = activeSection.prevAll();

var about = [];
prev.each(function(){ 
     about.push($(this).data('about'));
});

Alternatively, you can use a jQuery map as adeneo noted, or you can do this in a non-jQuery forEach loop.

var prev = activeSection.prevAll();

var about = [];
prev.forEach(function() {
  var val = $(this).data('about');
  about.push(val);
});
Sign up to request clarification or add additional context in comments.

2 Comments

great options here! appreciate it
what if i would want to check if a certain element has a class matching any of the returns in the array?
1

You'll have to map the data values to get an array of values

var prev = activeSection.prevAll();

var about = prev.map(function(){ 
     return $(this).data('about');
}).get();

2 Comments

great! very simple! wish i can accept both answers :(
what if i would want to check if a certain element has a class matching any of the returns in the array?

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.