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
6 Answers
Reset to default 6Use 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
版权声明:本文标题:javascript - Hide <li> when href is empty - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744209748a2595364.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论