Reputation: 25
this is my html list-
<ul id="board">
<li class="card" id="card1a">1</div>
<li class="card" id="card1b" >2</div>
<li class="card" id="card2a" >3</div>
<li class="card" id="card2b" >4</div>
</ul>
I made to an array in javaScript:
var cards=document.getElementsByClassName("card");
Than I tried to replace elements inside the array-
var temporaryValue = cards[0];
cards[0] = cards[2];
cards[2] = temporaryValue;
It didn't work: cards[0] and card[2] stayed in the same values. I don't know why. Please help!
Upvotes: 1
Views: 1028
Reputation: 86505
document.getElementsByClassName
doesn't return an array. It returns a live HTMLCollection -- an array-like object (ie: an object that presents a similar API) that contains matching elements in document order. The contents reflect the actual state of the document, you can't just swap stuff around in it.
If you want to swap the elements themselves, you can use the DOM to do it. (As you do that, the changes will propagate to your list as well.) If you just want to have an array you can swap entries around in, then copy the list to an array of your own.
Upvotes: 0
Reputation: 296
with the .getElementsByClassName("card"); you just get the reference of the html element and not the value directly, you can use innerText to replace and to get the text inside the element.
var temporaryValue = cards[0].innerText;
cards[0].innerText = cards[2].innerText;
cards[2.innerText = temporaryValue;
Hope it helps!
Upvotes: 0
Reputation: 10148
Looks like you are trying to change the textContent
This is how you do it
cards[0].textContent = cards[2].textContent
var cards=document.getElementsByClassName("card");
cards[0].textContent = cards[2].textContent
<ul id="board">
<li class="card" id="card1a">1</li>
<li class="card" id="card1b" >2</li>
<li class="card" id="card2a" >3</li>
<li class="card" id="card2b" >4</li>
</ul>
Upvotes: 2