Hide <li> when href is empty.

I want to hide any LI in a .social menu with empty hrefs.

I originally had:

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

But it only hides the link.

I thought that instead I could use:

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

But he does not add a hidden class.

HTML:

 <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> 
+4
source share
6 answers

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

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

(Also remember to use href="" instead of href*="" ).

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

+1
source

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

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

Note that .has() more efficient than :has() : http://jsperf.com/jquery-has-vs-has Although :has() read IMHO a bit.

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

It works:

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

I compiled this little jsFiddle to illustrate your scenario. You are using the "contains" selector (* =), which means that it is looking for an href containing nothing. Rather, I just explicitly check for an empty href, just using "=".

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

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

0
source

Source: https://habr.com/ru/post/1396786/


All Articles