Home > Software engineering >  List element getAttribute("value") returns wrong values after calling another function (sw
List element getAttribute("value") returns wrong values after calling another function (sw

Time:04-05

I am still learning Javascript and don't understand why I get wrong values when calling getAttribute('data-value') from removeButton after swapping elements with swapping() function.

const addButton = document.querySelector('.addButton');
const swapButton = document.querySelector('.swapButton');
var input = document.querySelector('.input');
const draggable_list = document.getElementById('draggable-list');

let items; 
const array = [];
const listItems = [];
let dragStartIndex;

class item {
    constructor(itemName) {
        this.createDiv(itemName);
    }
    createDiv(itemName) {
        let input = document.createElement('input');
        input.value = itemName;
        input.disabled = true;
        input.classList.add('item_input');
        input.type = 'text';
        
        let removeButton = document.createElement('button');
        removeButton.innerHTML = 'REMOVE';
        removeButton.classList.add('removeButton');

        draggable_list.appendChild(items);
        items.appendChild(removeButton);

        removeButton.addEventListener('click', (event) => {
            let itemNumber = event.target.closest('li').getAttribute('data-value');
            console.log("The deleted number has a value of: ", itemNumber); //returns wrong 'data-value' numbers
            if (event && event.target.parentElement) {
                this.remove(event.target.parentElement, input.value);
            }
        });
    }
    //Remove numbers
    remove(item, value) {
        draggable_list.removeChild(item);

        //delete from array
        let indexArray = array.indexOf(value);
        array.splice(indexArray,1);

        //delete from listItems
        listItems.splice(indexArray,1);

        //redfine indexes of li elements after deletion 
        array.forEach((numbers,index) => {
            items.setAttribute('data-index', index);
            items.setAttribute('data-value', numbers);
        } );
    }
}
//Create numbers
async function create() {
    if (input.value != '') {
        array.push(input.value);
        array.forEach((numbers,index) => {
            //if numbers already exists in the UI, then pass?
            items = document.createElement('li');
            items.setAttribute('data-index', index);
            items.setAttribute('data-value', numbers);
            items.innerHTML = `
            <div  draggable="true">
                <p  id="div">${numbers}</p>
                <i ></i>
            </div>`;
        } );
        listItems.push(items); //used for swapping
        new item(input.value);
        input.value = ''
    }
}
// Swap list items 
function swapItems(fromIndex, toIndex) {
    const itemOne = listItems[fromIndex].querySelector('.draggable');
    const itemTwo = listItems[toIndex].querySelector('.draggable');

    //swap UI items
    listItems[fromIndex].appendChild(itemTwo);
    listItems[toIndex].appendChild(itemOne);

    //swap array items
    [array[fromIndex], array[toIndex]] = [array[toIndex], array[fromIndex]];
    console.log("This is array after swapping: ",array);

    //redefine li index and values
    array.forEach((numbers,index) => {
        items.setAttribute('data-index', index);
        items.setAttribute('data-value', numbers);

        console.log("The values of the numbers aftwer swapping are: ", numbers); //'data-value' numbers are correct here
    } )
}

function swapping(){
    const draggables = document.querySelectorAll('.draggable'); 
    const dragListItems = document.querySelectorAll('.draggable-list li'); 

    draggables.forEach(draggable => {
        draggable.addEventListener('dragstart', dragStart);
    });

    dragListItems.forEach(item => {
        item.addEventListener('dragover', dragOver);
        item.addEventListener('drop', dragDrop);
    });
}

function dragStart() {
    dragStartIndex =  this.closest('li').getAttribute('data-index');
  }
function dragOver(e) {
    e.preventDefault();
}
function dragDrop() {
    const dragEndIndex =  this.getAttribute('data-index');
    swapItems(dragStartIndex, dragEndIndex);
}

addButton.addEventListener('click', create);
swapButton.addEventListener('click', swapping);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <link rel="stylesheet" href="style.css"> -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://kit.fontawesome.com/4690c1252a.js" crossorigin="anonymous"></script>
</head>
<body>

    <h1><span >Add a  number</span> </h1>
    <div >
        <input type="text"  placeholder="Add Task" />
        <button > </button>
        <button >SWAP</button>
    </div>

    <ul  id="draggable-list"></ul>
    <script src="code.js"></script>

</body>
</html>

If I try inserting the numbers 1, 2, 3 for example, I swap 1 with 2. Then delete 1, itemNumber will have a vlue of 2 instead of 1. Why is that?

CodePudding user response:

const addButton = document.querySelector('.addButton');
const swapButton = document.querySelector('.swapButton');
var input = document.querySelector('.input');
const draggable_list = document.getElementById('draggable-list');

let items;
const array = [];
const listItems = [];
let dragStartIndex;

class item {
  constructor(itemName) {
    this.createDiv(itemName);
  }
  createDiv(itemName) {
    let input = document.createElement('input');
    input.value = itemName;
    input.disabled = true;
    input.classList.add('item_input');
    input.type = 'text';

    let removeButton = document.createElement('button');
    removeButton.innerHTML = 'REMOVE';
    removeButton.classList.add('removeButton');

    draggable_list.appendChild(items);
    items.appendChild(removeButton);

    removeButton.addEventListener('click', (event) => {
      let itemNumber = event.target.closest('li').dataset.value;
      console.log("The deleted number has a value of: ", itemNumber);
      if (event && event.target.parentElement) {
        this.remove(event.target.parentElement, itemNumber);
      }
    });
  }
  //Remove numbers
  remove(item, value) {
    draggable_list.removeChild(item);

    //delete from array
    let indexArray = array.indexOf(value);
    array.splice(indexArray, 1);

    //delete from listItems
    listItems.splice(indexArray, 1);

    //redfine indexes of li elements after deletion 
    array.forEach((numbers, index) => {
      draggable_list.children[index].dataset.index = index;
      draggable_list.children[index].dataset.value = numbers;
    });
  }
}
//Create numbers
async function create() {
  if (input.value != '') {
    array.push(input.value);
    array.forEach((numbers, index) => {
      //if numbers already exists in the UI, then pass?
      items = document.createElement('li');
      items.dataset.index = index;
      items.dataset.value = numbers;
      items.innerHTML = `
                <div  draggable="true">
                    <p  id="div">${numbers}</p>
                    <i ></i>
                </div>`;
    });
    listItems.push(items); //used for swapping
    new item(input.value);
    input.value = ''
  }
}
// Swap list items 
function swapItems(fromIndex, toIndex) {
  const itemOne = listItems[fromIndex].querySelector('.draggable');
  const itemTwo = listItems[toIndex].querySelector('.draggable');

  //swap UI items
  listItems[fromIndex].prepend(itemTwo);
  listItems[toIndex].prepend(itemOne);

  //swap array items
  [array[fromIndex], array[toIndex]] = [array[toIndex], array[fromIndex]];
  console.log("This is array after swapping: ", array);

  //redefine li index and values
  array.forEach((numbers, index) => {
    draggable_list.children[index].dataset.index = index;
    draggable_list.children[index].dataset.value = numbers;

    console.log("The values of the numbers after swapping are: ", numbers);
  })
}

function swapping() {
  const draggables = document.querySelectorAll('.draggable');
  const dragListItems = document.querySelectorAll('.draggable-list li');

  draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', dragStart);
  });

  dragListItems.forEach(item => {
    item.addEventListener('dragover', dragOver);
    item.addEventListener('drop', dragDrop);
  });
}

function dragStart() {
  dragStartIndex =  this.closest('li').dataset.index;
}

function dragOver(e) {
  e.preventDefault();
}

function dragDrop() {
  const dragEndIndex =  this.dataset.index;
  swapItems(dragStartIndex, dragEndIndex);
}

addButton.addEventListener('click', create);
swapButton.addEventListener('click', swapping);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- <link rel="stylesheet" href="style.css"> -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://kit.fontawesome.com/4690c1252a.js" crossorigin="anonymous"></script>
</head>

<body>

  <h1><span >Add a number</span> </h1>
  <div >
    <input type="text"  placeholder="Add Task" />
    <button > </button>
    <button >SWAP</button>
  </div>

  <ul  id="draggable-list"></ul>
  <script src="code.js"></script>

</body>

</html>

  • Related