0

Is there a way to target only li elements where the a tag has a specific class?

for example:

<li> <a href="#" class="mobile-only">link</a> </li>
<li> <a href="#" class="other-class">link</a> </li>

Can I just target the li where a has class "mobile-only"?

Florin Simion
  • 426
  • 9
  • 17

3 Answers3

6

you can access the parent of anchor tag with class mobile-only

$( "a.mobile-only" ).parent();

or you can use parent pseudo selector, but there are performance concerns

li a:parent { background: none; }

js Code $( "li a:parent" )

also the has selector

li:has(a.mobile-only) { background: none; }

js Code $( "li:has(a.mobile-only)" )

Community
  • 1
  • 1
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
0

This is very easy to do with jQuery.

Just do:

$("a.mobile-only").parents("li")
Sarhanis
  • 1,517
  • 12
  • 19
  • 1
    `.parent()` would be more appropriate here than `.parents()`. – Daniel Beck Feb 26 '16 at 13:45
  • @DanielBeck is right as this may be nested within other `li`'s – Jamie Harding Feb 26 '16 at 13:46
  • parent() is more appropriate if you're sure that the li is the direct parent. Otherwise parents() is better. – Sarhanis Feb 26 '16 at 13:47