Jesse C Jesse C - 6 months ago 35
jQuery Question

jquery find element and add class to element

Trying to add a class to an element inside an li item when a function call is made. I can get the correct value outputted, however finding the child

<i>
is proving difficult. If I could find the correct nested
<i>
and add the class 'show' that would solve it :)

JS code:

filterMarkers = function(category) {
for (i = 0; i < markers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
// Show the tick icon
$(".filter").find("[data-value='" + category + "']").addClass('show');

}
// Categories don't match
else {
marker.setVisible(false);
}
}
}


HTML code:

<ul class="drop-down">
<li class="filter blue" data-value="" onclick="filterMarkers('');">All <i class="fi-check"></i></li>
<li class="filter yellow" data-value="test-one" onclick="filterMarkers('test-one');">Sales <i class="fi-check"></i></li>
<li class="filter red" data-value="test-two" onclick="filterMarkers('test-two');">Incentives <i class="fi-check"></i></li>
<li class="filter grey" data-value="test-three" onclick="filterMarkers('test-three');">Conferences <i class="fi-check"></i></li>
<li class="filter orange" data-value="test-four" onclick="filterMarkers('test-four');">Team building <i class="fi-check"></i></li>
</ul>

Answer

Looking at the filterMarkers method, you

  1. Either want to simply show the category which is passed as argument and hide everything else

  2. Or if no argument is passed then hide everything.

Simplify your code to

filterMarkers = function(category) {
    $(".filter").removeClass("show"); //remove show class from all
    if( category.length > 0 )
    {
       $(".filter[data-value='" + category + "']").addClass('show');
    }
    for (i = 0; i < markers1.length; i++) 
    {
        marker = gmarkers1[i];
        marker.category == category || category.length === 0 ? marker.setVisible( true ) : marker.setVisible( false );
        }
    }
}
Comments