admin管理员组

文章数量:1399347

I want to hide any LI in .social-menu that have blank hrefs.

I originally had:

$('ul.social-menu li a[href*=""]').hide();

But it only hides the link.

I thought perhaps instead I could use:

$('ul.social-menu li a[href*=""]').addClass('hidden')

But it is not adding the class hidden.

The HTML is:

<ul class="social-menu">
   <li class="facebook"><a target="parent" href=""></a></li>
   <li class="twitter"><a target="parent" href="!/dft_au">Twitter</a></li>
</ul>

I want to hide any LI in .social-menu that have blank hrefs.

I originally had:

$('ul.social-menu li a[href*=""]').hide();

But it only hides the link.

I thought perhaps instead I could use:

$('ul.social-menu li a[href*=""]').addClass('hidden')

But it is not adding the class hidden.

The HTML is:

<ul class="social-menu">
   <li class="facebook"><a target="parent" href=""></a></li>
   <li class="twitter"><a target="parent" href="http://twitter./#!/dft_au">Twitter</a></li>
</ul>
Share Improve this question edited Feb 16, 2012 at 9:16 Justin asked Feb 16, 2012 at 9:00 JustinJustin 3292 gold badges9 silver badges19 bronze badges 1
  • You need to use the has selector. your selector hides the <a> anchor only. – gdoron Commented Feb 16, 2012 at 9:11
Add a ment  | 

6 Answers 6

Reset to default 6

Use the :has() selector or the has() method to select all <li> elements that contain an anchor (<a>) with an empty href attribute value:

$('ul.social-menu li:has(a[href=""])').hide();
// or…
$('ul.social-menu li').has('a[href=""]').hide();

Note that .has() is more efficient than :has(): http://jsperf./jquery-has-vs-has Although :has() is slightly more readable IMHO.

$('ul.social-menu li:has(a[href=""])').hide();

An alternative to .has/:has which in my option is simpler and most likely more efficient would be .parent() (or .closest("li") if the li isn't the direct parent of the link):

$('ul.social-menu li a[href=""]').parent().hide();

(Also don't forget to use href="" instead of href*="").

EDIT: It is much more efficient: http://jsperf./jquery-has-vs-has-vs-parent

I piled this little jsFiddle to illustrate your scenario. You are using the "contains" selector (*=), which means it's looking for an href containing nothing. Rather just explicitly test for an empty href by just using "=".

This works:

$('ul.social-menu li').has('a[href=""]').hide();
listItems = ​$('ul li a');

$.each(listItems, function() {
  if($(this).attr('href') == '') {
    $(this).parent().remove();
  } 
});​

http://jsfiddle/YZwRH/1/

本文标签: javascriptHide ltligt when href is emptyStack Overflow