Reputation: 4642
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
Reputation: 74420
You could use :has() jquery selector:
$("li:has(a:contains('Testing'))")
Or .has() method:
$('li').has("a:contains('Testing')")
Upvotes: 0
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