简体   繁体   中英

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:

  • by clicking onto the servicenext button,
  • the code gets the id of the div in the href
  • the addClass is applied to the li with the same href

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');
}); 
});

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM