Phorce
Phorce

Reputation: 4642

Selecting the "li" element after the a tag

Basically,

I have a navigation that looks something like this:

<li><a href="#">Testing</a></li>

What I need to do is add a class to the <li> tag that is directly before it. The link would therefore look like so:

<li class="active"><a href="#">Testing</a></li>

I have tried to use the following:

 $(document).find("a:contains('Testing')").each(function(){
    var element=$(this);

  });

I therefore assume that element refers to the a tag, but, even when I have tried to use .prev() it still does not select the right tag.

What can I use to select the <li> element?

Upvotes: 1

Views: 70

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

You could use :has() jquery selector:

$("li:has(a:contains('Testing'))")

Or .has() method:

$('li').has("a:contains('Testing')")

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

li element is parent of anchor tag. You need to use .parent() or .closest() instead of using .prev():

$("a:contains('Testing')").parent().addClass('active');

or

$("a:contains('Testing')").closest('li').addClass('active');

Upvotes: 3

Related Questions