简体   繁体   中英

How to hide all elements except the last one (by class) using jQuery

I have a menu that looks like this (1 list item as an example):

<ul class="dyn makeLink" style="display: block;">
    <li id="licategory_1">
        <a href="/nfl-lines" title="" class="linkItem">
            <strong>NFL</strong>
        </a>
        <span class="expCollPos" >
            <span class="collapsed"></span>
        </span>
        <span class="expCollPos linkItem" >
            <span class="collapsed"></span>
        </span>
        <span class="expCollPos" >
            <span class="collapsed"></span>
        </span>
    </li>


    <li id="licategory_2">
    ... 
    </li>

</ul>

Which has for some strange reason 3 spans(.expCollPos), the two first ones aren't relevant for me and I'm trying to remove ONLY them using jQuery.

I tried using: $('.dyn li span.expCollPos:last-child').css("display", "none");

and several others - but it just removes all of the .expCollPos classes.

Am I doing something wrong?

(I got a code that I have to edit and it looks horrable! The javascript functions are unclear and the CSS has so much "!important" that I cant find what's what. )

您想隐藏除最后一个以外的所有内容,因此您必须说不像最后一个一样

$('.dyn li').find('span.expCollPos:not(:last)').hide();

Try

$(".dyn li span.expCollPos").slice(-1).hide();

 $(".dyn li span.expCollPos").slice(-1).hide() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul class="dyn makeLink" style="display: block;"> <li id="licategory_1"> <a href="/nfl-lines" title="" class="linkItem"> <strong>NFL</strong> </a> <span class="expCollPos" > <span class="collapsed">1</span> </span> <span class="expCollPos linkItem" > <span class="collapsed">2</span> </span> <span class="expCollPos" > <span class="collapsed">3</span> </span> </li> <li id="licategory_2"> </li> </ul> 

用这个

$('#licategory_1 span.expCollPos').eq(2).show();
$('body').find('.teads-inread:not(:last)').hide();

https://jsfiddle.net/mbrasil/n0reckgv/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM