Dheeraj Agrawal Dheeraj Agrawal - 29 days ago 20
Javascript Question

Change innerHTML of clicked element javascript

I have 4 cards and I want to change the text of its element on click, below is my html:

<tr>
<td class="card">down</td>
<td class="card">down</td>
</tr>
<tr>
<td class="card">down</td>
<td class="card">down</td>
</tr>


So if I click on any card its text should be up and others should be down. I am able to change the text of clicked card but how I can change back other cards value to down? Below is my JS

var cards = document.getElementsByClassName('card');

for (var i = 0; i < cards.length; i++) {
cards[i].onclick = function(target) {
this.innerHTML = 'up';
}
}

Answer

You can do it like:

var cards = document.getElementsByClassName('card');
for (var i = 0; i < cards.length; i++) {
  cards[i].onclick = function(target) {
    // Turn the 'cards' into an array and loop over it.
    [].forEach.call(cards, function(card) { 
      card.innerHTML = "down" 
    });
    this.innerHTML = "up";
  }
}

This will loop over all the cards and return their values to "down".

Fiddle

Demo below

var cards = document.getElementsByClassName('card');
for (var i = 0; i < cards.length; i++) {
  cards[i].onclick = function(target) {
		[].forEach.call(cards, function(card) { card.innerHTML = "down" });
    this.innerHTML = "up";
  }
}
<table>

  <tr>
    <td class="card">down</td>
    <td class="card">down</td>
  </tr>
  <tr>
    <td class="card">down</td>
    <td class="card">down</td>
  </tr>
</table>

Comments