how do i change the text of a div to the text of another div?

One solution would be to keep a global for holding a reference to the selected div, then adding a click event to all div’s with className box, on the click event check to see if the global is null, if not switch it’s value with the previously selected div, else store a reference to the selected div

let switchBox = null;

const boxes = document.querySelectorAll('.box');

for(let i = 0; i < boxes.length; i++){
   boxes[i].addEventListener('click', function(){
       SwitchValues(this);
   });
}

function SwitchValues(box){
   if(switchBox === null){
      switchBox = box;
   }else{
      const switchText = switchBox.textContent;
      const boxText = box.textContent;
      box.textContent = switchText;
      switchBox.textContent = boxText;
      switchBox = null;
   }
}
<div class='cards'>
        <div class='box'>7</div>
        <div class='box'>6</div>
        <div class='box'>15</div>
        <div class='box'>8</div>
        <div class='box'>3</div>
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top