-3

I want to add an active class to a nav element, but i don't get it working. My code is:

$(document).ready(function() {
    if ($('a[href="<?php echo RoutingClass::getView(); ?>"]') == $('a[href="home"]')) {
        $('a[href="home"]').addClass('active');
    }
});

and when its parsed in the browser, it looks like this (on the homepage):

$(document).ready(function() {
    if ($('a[href="home"]') == $('a[href="home"]')) {
        $('a[href="home"]').addClass('active');
    }
});

when i leave out the if comparison, it just adds the active class, but in it, it doesnt.

Milap
  • 6,915
  • 8
  • 26
  • 46
Medina
  • 13
  • 4

3 Answers3

0

See jQuery object equality for a discussion about jquery equality.

My suggestion for your code is this:

$(document).ready(function() {
    if (<?php echo RoutingClass::getView()=='home'?'1':'0' ?>)) {
        $('a[href="home"]').addClass('active');
    }
});
Community
  • 1
  • 1
Chris Lear
  • 6,592
  • 1
  • 18
  • 26
0

You are comparing 2 DOM elements.

Lets use an IDfor each of anchor tags, I've called them a1 and a2 :

$('a#a1').attr('href') == $('a#a2').attr('href')
SalmanShariati
  • 3,873
  • 4
  • 27
  • 46
0

You can check if that jQuery element you select has the home href like that:

$('a[href="home"]').attr("href") == "home"

Your code will work like that:

$(document).ready(function() {
if ( $('a[href="home"]').attr("href") == "home" ) {
    $('a[href="home"]').addClass('active');
}});
Clemens Himmer
  • 1,340
  • 2
  • 13
  • 26