Leff Leff -4 years ago 27
Javascript Question

Getting text from all the links that have the same class

I have filters where I toggle class active on click. On click I would also like to loop through the links that have the class active and make a new array out of the text of those links. But I don't get anything in the console when I am looping through.
This is the code:

$('.filter-button').click(function() {

$(this).toggleClass('active');

var activeTags = $('filter-button.active');

$(activeTags).each(function() {
var tags[] = $(this.text());
});

console.log(tags);
});


What am I doing wrong?

Answer Source

You're creating a new tags variable, local to the each() function, for each element. That's thrown away when the function exits.

Your outer console.log() is trying to list the value of something that does not exist (since we're no longer inside the each() function).

Create, and append to, an array outside of each():

$('.filter-button').click(function() {

  $(this).toggleClass('active');

  var activeTags = $('.filter-button.active');
  var tags = [];

  $(activeTags).each(function() {
    tags.push($(this).text());
  });

  console.log(tags);
});
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class=filter-button>1</button>
<button class=filter-button>2</button>
<button class=filter-button>3</button>
<button class=filter-button>4</button>
<button class=filter-button>5</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download