Jesper Ong
Jesper Ong

Reputation: 23

Dynamic code to addClass to an element specified in the link

I'm trying to add a class to an element specified within my HTML from clicking on a button.

HTML:

<div id="servicenext"><a href="#nav2"><p class="four">next</p></a>

Script:

$('#servicenext a').click(function(){
     $('ul.navigation a').removeClass('active');
     $(*the div in the href*).addClass('active');
}); 

I'm hoping to have code that's dynamic. Basically it'll work by adding the class to any element specified in the a href. This is because i have quite a handful of these and do not wish to code them individually.

EDIT:

Thanks James! that's great! But I do have to apologize, i was confused myself at what I was asking for! What I'm actually looking to addClass to was actually the li in ul.navigation a

So if I'm thinking right, im trying to do this:

I'm guessing there should be if else statements somewhere, forgive me, i'm not really a programmer.

the gibberish i came up with is:

$('#servicenext a').click(function(){
     $('ul.navigation a').removeClass('active');
     $($(this).attr("href").find($('ul.navigation li a').attr("href"))).addClass('active');
}); 
});

Upvotes: 0

Views: 87

Answers (1)

James Allardice
James Allardice

Reputation: 166071

Since the value of the href attribute is already a valid ID selector, you can simply use the value of the attribute:

$($(this).attr("href")).addClass('active');

Note that you have to get the actual attribute value. The native DOM property returns an actual URL, not just the value of the attribute.

Here's a working example.

Upvotes: 4

Related Questions