Reputation: 329
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
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
Reputation: 2910
listItems = $('ul li a');
$.each(listItems, function() {
if($(this).attr('href') == '') {
$(this).parent().remove();
}
});
Upvotes: 0
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
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