How to add a class to a parent li with jquery

Hi There,

  • I’ve got a list similar to the following:

<ul>
<li><a href=“item1.php”>item1</a></li>
<li><a href=“item3.php”>item2</a>
<ul>
<li><a href=“item2-5.php”>item2-5</a></li>
</ul</li>
<li><a href=“item3.php”>item3</a></li>
</li>

  • Item 2-5 needs to have a class added either to the a or the li using jquery I’ve tried the following but it isn’t working:

<script>
jQuery(function(){
$(this).parent(‘li’).addClass(‘current’);
});
</script>

I’m new to this jquery malarkey so I’m shooting in the dark somewhat here so if anyone can point me in the right direction is would be most appreciated.
I should mention that there’ll be a few of these nested lists, the parents (li) of which will all need a class added via jquery.

Thanks,
Dan

I know I originally gave incorrect details and I apologise for that. If what I’m trying to achieve really isn’t possible then please tell me so I’m not going on a wild goose chase. Thanks.

Hi There,

Thanks for the suggestion but there’ll be other subcategories created over time by my client and ideally I need a method of adding the class regardless of the link each time a new subcategory is added.

Cheers,
Dan

Good grief yes! Sorry, I’m overworked and underslept…that’s my excuse anyway. Yes that is exactly what I want styled and I’m sorry to send you on a wild goose chase.

$(‘a[href=item2-5.php]’).parent().addClass(‘current’);

How will the current link be determined?

If the page refreshes each time a link is clicked the current class should be applied at the server level not the client level. I don’t really see the advantages of using JavaScript to apply the current link unless the pages isn’t refreshing. In that case you will also need to account for removing the current class from the link that was previous clicked also, not just adding it to the link that was clicked. None the less, the logic that is necessary to differentiate the current vs. not current link is critical to the operation of this feature.

Hello again.

Any ideas? I’m still somewhat at a loose end with this menu and some more help would be most appreciated.

Thanks,
Dan

In that case wouldn’t you want the class added to item-2, instead of item-2-5?

Well it was primarily the <li> that I wanted to style - the link itself being styled would do also. The fact is that I’m using the opencart ecommerce system and it has no built in way to style parent categories so I thought that using javascript to insert a class into every parent <li>l (i.e. an <li> that has a nested <ul>).
What I need to do is add an arrow image next to each parent category in a list to indicate a second level dropdown list on hover. Normally this would be a piece of cake of course - add the class by hand but not when the list is being dynamically created by php and I have no php skills. Therefore a javascript solution (ideally jquery as the library is already in use by the site) would be immensely helpful
Thanks,
Dan