1

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!

2
  • Are you trying to change the values in html list (ul and li) our just inside the cards variable? Commented May 8, 2018 at 19:57
  • You're just changing element references around, not the actual <li> elements they're pointing to. If you want to "change" the HTML, you need to remove a <li>, then insert it elsewhere. Commented May 8, 2018 at 19:57

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks, that was my mistake.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.