简体   繁体   中英

Count and hide links if 1 or less. Jquery

I have a div set up that has dynamically loaded links.

<div class="module">
    <a href="#" class="sidelink">
    <a href="#" class="sidelink">
</div>

How can I set this up so that if their is 1 link or less in this div, to hide all (in this case the 1) link. Looking for a simple jquery solution/

Assuming you have many such sections you can do:

$('.module:not(:has("a:nth-of-type(2)"))').hide();

Fiddle

  • nth-of-type
  • not
  • has

  • .module - selects all the module elements

  • a:nth-of-type(2) - selects any anchor with the index of 2 ie if you have more that 1 anchor
  • see a has selector, it now combined above 2 exprs to select module having anchor 2 or more, but hold on
  • a not selector wrapping the above 2 ensure it selects modules that doesn't satisfy the above conditions.

Inorder to hide the modules, try:

$('.module:not(:has(a:gt(0)))').find('a').hide();

Fiddle

or just

$('.module a').filter(function(){
    return $(this).siblings('a').length == 0;
}).hide();

toggle() will hide/show based on a boolean, checking if there are more than one anchor would evaluate as true or false :

$('.module a').toggle($('.module a').length > 1);

and close the anchors.

if ($('.sidelink').length === 1) {
    $('.module').hide();
}

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