0

I'm sure this is very easy but its a friday afternoon and my brain is a little frazzled.

Any help would be appreciated I am looking to traverse to an 'a' tag within a 'li' tag. The li tag has a class of 'menu-item-has-children'. I am trying to add a class to the 'a' tag.

Here is sample markup

<li class="menu-item-has-children">
<a>Item</a>
<ul>some other stuff</ul>
</li>

Any advice on a simple jquery/vanilla approach to doing this?? Thanks :-)

CraigDev
  • 113
  • 1
  • 12
  • How you traverse to the `a` would depend entirely on what element you're starting from, ie. the element which raised an event. – Rory McCrossan Jul 14 '17 at 14:07
  • `$('li.menu-item-has-children a').addClass(...)` ? – Lorenzo Marcon Jul 14 '17 at 14:10
  • This certainly does the trick - problem I have though is there are also 'a' tags in the accompanying 'ul'. Is there a way to only target the first child? – CraigDev Jul 14 '17 at 14:14
  • 1
    Yep, use the child operator: `$('li.menu-item-has-children > a').addClass(...)`. Also, just a note on your terminology, this isn't traversal, it's a selector. Traversal is where you have a reference to an element in memory and then use traversal methods to move up/down/aside in the DOM tree to find another related element. – Rory McCrossan Jul 14 '17 at 14:17
  • This did the trick! thank you :-) – CraigDev Jul 14 '17 at 14:27

1 Answers1

0

Just like the comments say, this should work unless you are trying to get to a specific a within a specific li.menu-item-has-children, then it would depend on where you are starting from.

$('li.menu-item-has-children a').addClass(...)
CumminUp07
  • 1,936
  • 1
  • 8
  • 21