Justin
Justin

Reputation: 329

Hide <li> when href is empty

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.com/#!/dft_au">Twitter</a></li>
</ul>

Upvotes: 4

Views: 1398

Answers (6)

RoToRa
RoToRa

Reputation: 38410

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.com/jquery-has-vs-has-vs-parent

Upvotes: 1

sidneydobber
sidneydobber

Reputation: 2910

listItems = ​$('ul li a');

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

http://jsfiddle.net/YZwRH/1/

Upvotes: 0

Mathias Bynens
Mathias Bynens

Reputation: 149584

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.com/jquery-has-vs-has Although :has() is slightly more readable IMHO.

Upvotes: 6

Hadas
Hadas

Reputation: 10374

This works:

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

Upvotes: 0

gdoron
gdoron

Reputation: 150253

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

Upvotes: 2

FarligOpptreden
FarligOpptreden

Reputation: 5043

I compiled 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 "=".

Upvotes: 0

Related Questions