Christian Trick
Christian Trick

Reputation: 15

JS / jQuery - Extend Var in each()-function

I have two lists in this format:

<ul id="filters" class="option-set button-group" data-filter-group="kategorie">
    <li>
        <a href="#" data-filter=".corporatedesign">Corporate Design</a>
    </li>
    <li>
        <a href="#" data-filter=".webdesign">Webdesign</a>
    </li>
</ul>

In Javascript there is a click-function which addes or removes the class "isotopeactive" to the link-element:

$('#filters a').click(function(){
    var $this = $(this);                
    if ( $this.hasClass('isotopeactive') ) {
        $this.removeClass('isotopeactive');
    }else{
        $this.addClass('isotopeactive');
    }

The problem is to get all the data-filter - data from all elements that are "isotopeactive" into one variable. My first try was this, but it does not work..

var filterValue = '';
var i = 0;  

$( ".isotopeactive" ).each(function() {
    filterValue += $this.attr('data-filter');
    i++;
});

In the end i want to get something like this: filterValue => ".corporatedesign .webdesign"

Any suggestions? Thanks! :)

Upvotes: 0

Views: 92

Answers (1)

David Thomas
David Thomas

Reputation: 253466

I'd suggest:

var data = $('.isotopeactive').map(function(){
             return this.dataset.filter;
           }).get();

For those, older, browsers that don't implement dataset:

var data = $('.isotopeactive').map(function(){
             return this.getAttribute('data-filter');
           }).get();

Or:

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

This will return an array of values to the data variable.

References:

Upvotes: 1

Related Questions