Premalatha
Premalatha

Reputation: 41

Adding class using JS on a click of an anchor tag

<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

Answers (2)

Premalatha
Premalatha

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

mplungjan
mplungjan

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

Related Questions