Reputation: 41
<p id="testhome-1">Test</p>
<p id="testhome-2">Test</p>
<a href="#testhome-1">Click</a>
<a href="#testhome-2">Click</a>
When I click the anchor tag, I want to add a class to a particular id of Paragraph.
Upvotes: 1
Views: 4828
Reputation: 41
While surfing I found an alternate code to add class to a particular id when i click to anchor tag. It works for me. I don't know if it suits for all browsers.
Here I attached the code.
$("a").on("click", function() {
var id = $(this).attr('href');
$('.active').removeClass('active'); // remove existing active
$(id).addClass('active'); // set current link as active
});
Refer jsfiddle: http://jsfiddle.net/PremalathaKumar/3J9WK/109/
Upvotes: 1
Reputation: 178403
Plain JS:
window.onload=function() {
document.querySelector("[href=#testhome-1]").onclick=function() {
document.querySelector("#testhome-1").classList.add("clicked"); // or toggle
return false; // cancel link
}
}
or for any link:
window.onload = function() {
var links = document.querySelectorAll("a");
for (var i=0;i<links.length;i++) {
links[i].onclick = function() {
document.querySelector("#"+this.href.split("#")[1]).classList.toggle("clicked");
return false; // cancel link
}
}
}
.clicked { color:green }
<p id="testhome-1">Test</p>
<p id="testhome-2">Test</p>
<a href="#testhome-1">Click 1</a> |
<a href="#testhome-2">Click 2</a>
Upvotes: 1