atlMapper
atlMapper

Reputation: 764

modify parent of specified li element JS

I'm new to using 'this', but if I am understanding this correctly, I can only use this inside a function defined within another.

In this case I am selecting a li item based on its a href and I need to add a class if it meets the criteria. I feel like I'm close but missing something small, 'url[1]' is from a split.

if ($('#Navbar li a:contains(' + url[1] + ')').attr('href')) {
    function () {
        $(this).parent().addClass('active');
    }
}

EDIT: I am looping through my Li objects based and comparing the href's to look for a match. Thanks to everyone for helping me through this. I have a much better understanding of this now:

     $('#Navbar li a').each(function () {
     if ($(this).attr('href')==url[1]) {
            $(this).parent().addClass('active');
         }
     });

Upvotes: 1

Views: 62

Answers (4)

atlMapper
atlMapper

Reputation: 764

 $('#Navbar li a').each(function () {
 if ($(this).attr('href')==url[1]) {
        $(this).parent().addClass('active');
     }
 });

The loop was the trick. Thanks: @roasted @brenjt @Maverick

Upvotes: 2

AdityaParab
AdityaParab

Reputation: 7100

Simple! :)

if ($('Navbar li a:contains(' + url[1] + ')').attr('href')) {
    var that=this;
    function () {
        //your condition checking
        $(that).parent().addClass('active');
    }
}

UPDATE:: above code is WRONG

You can do it like this as well...

$('Navbar li a:contains(' + url[1] + ')').on('click',function(){
    if($(this).attr('href')){
        if(yourCOndition){
            $(this).parent().addClass('active');
        }
    }
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

$(this) not point to your targeted element (i think without seeing your full html code). Try following code:

var $a =$('Navbar li a:contains(' + url[1] + ')');
if ($a.attr('href')) {
        $a.parent().addClass('active');
}

Upvotes: 2

brenjt
brenjt

Reputation: 16297

this refers to the context in which it is being used. So this is referring to the anonymous function you created. A better solution to your problem would be:

var nav_item = $('Navbar li a:contains(' + url[1] + ')');

if (nav_item.attr('href')) {
    nav_item.parent().addClass('active');
}

Upvotes: 3

Related Questions