followconscience followconscience - 1 year ago 56
HTML Question

How to get 'bold attribute' only on clicked item

enter image description here

I have a question and I need some help. Here is my code:

function myFunction(id) {
document.getElementById(id).className = 'show_team';

.show_team {
font-weight: bold;
color: green;

<a id="1" href="#" onclick="myFunction(;">Team 1</a>
<a id="2" href="#" onclick="myFunction(;">Team 2</a>
<a id="3" href="#" onclick="myFunction(;">Team 3</a>
<a id="4" href="#" onclick="myFunction(;">Team 4</a>
<a id="5" href="#" onclick="myFunction(;">Team 5</a>
<a id="6" href="#" onclick="myFunction(;">Team 6</a>
<a id="7" href="#" onclick="myFunction(;">Team 7</a>
<a id="8" href="#" onclick="myFunction(;">Team 8</a>
<a id="9" href="#" onclick="myFunction(;">Team 9</a>
<a id="10" href="#" onclick="myFunction(;">Team 10</a>

I want to display link text in bold only the item that is last clicked. But I can't, because when I click one, other links remains bold too.

Answer Source

The class .show_team should be removed from all elements when clicked then added to the clicked element only.

I have updated the code, you don't need to add onclick function on every element anymore.

(function() {
  var aList = document.getElementsByClassName("link"); // list of elements
  for(var i = 0; i < aList.length; i++) {
    aList[i].addEventListener("click", function(element) {
      for(var i = 0; i < aList.length; i++) {   // loop through elements
        aList[i].classList.remove("show_team"); // and remove the class "show_team"
      // add class "show_team" to the clicked element"show_team");
.show_team {
  font-weight: bold;
  color: green;
<a id="1" class="link" href="#">Team 1</a>
<a id="2" class="link" href="#">Team 2</a>
<a id="3" class="link" href="#">Team 3</a>
<a id="4" class="link" href="#">Team 4</a>
<a id="5" class="link" href="#">Team 5</a>
<a id="6" class="link" href="#">Team 6</a>
<a id="7" class="link" href="#">Team 7</a>
<a id="8" class="link" href="#">Team 8</a>
<a id="9" class="link" href="#">Team 9</a>
<a id="10" class="link" href="#">Team 10</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download