Ramtin Gh
Ramtin Gh

Reputation: 1050

nth of type based on dynamic class

I have made a simplified version here: http://jsfiddle.net/Y5zYy/

I'm trying to add a different css style to the nth visible item of a list, so when the user clicks on group2 for example, I want the third Item of that group to turn black(Which is number 4), while currently the second item, which is the 3rd item of the whole list turns black.

Here is how it works: When you click on each group, items on that group will be added a class say "visible" then I want javascript to count visible items after each click and add some style to the nth visible item regardless of its number in the whole list.

HTML:

  <ul>
    <li class="g1">1</li>
    <li class="g1 g2">2</li>
    <li class="g1 g2">3</li>
    <li class="g1 g2">4</li>
    <li class="g1 g2">5</li>
    <li class="g1 g2">6</li>
    <li class="g1 g2">7</li>
    <li class="g1 g2">8</li>
    <li class="g1 g2">9</li>
    <li class="g1 g2 g3">10</li>
    <li class="g1 g2 g3">11</li>
</ul>
<a id="g1" href=#>Group1</a>
<a id="g2" href=#>Group2</a>
<a id="g3" href=#>Group3</a>

JS:

$(window).load(function(){


         $('li:nth-of-type(3)').css({
                                  "background-color":"#000",
                                   "font-weight":"bold",

      })



 $("li").addClass("visible");
$("a").click(function() {
             $("li").removeClass("visible");
             $('li').css({
                 "background-color":"red"
                                      })
               $(this).each(function() {
     $("." + $(this).attr('id')).addClass("visible");
   });
       if( $('li.visible').length > 3 ){
         $('li:nth-of-type(3)').css({
                                  "background-color":"#000",
                                   "font-weight":"bold",

      })
}
        });

});//]]>  

Upvotes: 0

Views: 888

Answers (1)

Terry
Terry

Reputation: 66123

If you're trying to target the 3rd <li> element in the group after hiding the rest, then you should use the :eq() selector in jQuery:

$('li:eq(2)').css({
    "background-color": "#000",
    "font-weight": "bold"
});

eq() starts from 0, so if you want to select the 3rd <li> you'll need to use :eq(2)

If you want to toggle the appearance of the element, may I recommend adding and removing classes, which makes it easier to reset to the default style when not needed:

$('li.visible:eq(2)').addClass('highlighted');

CSS:

.highlighted {
    background-color: #000;
    font-weight: bold;
}

Upvotes: 1

Related Questions