lovepeople lovepeople - 4 months ago 13
jQuery Question

Add class, closest div

Almost have 3 hours spend on this. Nothing found.

Here is my code.. 3 separate URL on file. (Updated)

<div id="menu">
<a href="blue.php">
<div class="list">
Content_here
</div>
</a>

<a href="yallow.php">
<div class="list">
Content_here
</div>
</a>

<a href="black.php">
<div class="list">
Content_here
</div>
</a>
</div>


Add class on current URL

<div id="menu">
<a href="#">
<div class="list active">
content_here
</div>
</a>
</div>


Here is:

$("#menu a").each(function(index) {
if($.trim(this.href) == window.location) {
$(this).closest('div').addClass("active");
}
});


No
active
class
on current
URL
. ...

Answer

The closest() method is using for getting the ancestor element.Since the div is inside the a use children() or find() method.

$(this).find('div').addClass("active");

Or select it based on the this context.

$('div', this).addClass("active");

Although for getting the current page url use window.location.href.

$("#menu a").each(function(index) {
    if($.trim(this.href) == window.location.href) {
        $('div', this).addClass("active");
    }
});

or use condition as window.location.pathname == $(this).attr('href')

Comments