-2

I'm looking for a method of changing the class of a selected id. I aim to do this with java but I can't seem to work out how. So in my example I have 4 "p" tags each with a different id and all with the class "na" now what I want to do is when one of the "p" tags is click it swaps the class to "under" and resulting in the tag being underlined. Can anyone point me in the right direction here to simplify it?

EDIT

Sorry guys, I forgot to add the JavaScript.

function class1() {
  document.getElementById("p1").className = "under";
  document.getElementById("p2").className = "na";
  document.getElementById("p3").className = "na";
  document.getElementById("p4").className = "na";
}

function class2() {
  document.getElementById("p1").className = "na";
  document.getElementById("p2").className = "under";
  document.getElementById("p3").className = "na";
  document.getElementById("p4").className = "na";
}

function class3() {
  document.getElementById("p1").className = "na";
  document.getElementById("p2").className = "na";
  document.getElementById("p3").className = "under";
  document.getElementById("p4").className = "na";
}

function class4() {
  document.getElementById("p1").className = "na";
  document.getElementById("p2").className = "na";
  document.getElementById("p3").className = "na";
  document.getElementById("p4").className = "under";
}
.under {
  font-size: 16px;
  font-weight: bold;
  text-decoration: underline;
}

.na {
  font-size: 16px;
  font-weight: bold;
}
<p id="p1" class="na" onclick="class1()">Para1</p>
<p id="p2" class="na" onclick="class2()">Para2</p>
<p id="p3" class="na" onclick="class3()">Para3</p>
<p id="p4" class="na" onclick="class4()">Para4</p>
G.Hamton
  • 61
  • 1
  • 1
  • 8

1 Answers1

0

It looks like you over-complicated the task.

Using jQuery, this is super simple to achieve in only one "two lines" function.

$(".na").on("click", function(){
  
  // Remove the class under from all p element.
  $(".na").removeClass("under");
  
  // Add the class under to the one clicked.
  $(this).addClass("under");
});
.under {
  text-decoration: underline;
}

.na {
  font-size: 16px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="p1" class="na">Para1</p>
<p id="p2" class="na">Para2</p>
<p id="p3" class="na">Para3</p>
<p id="p4" class="na">Para4</p>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64