-2
function addItem(e) {
 const li = document.createElement('li');
 li.className = "list-group-item";
 li.appendChild(document.createTextNode(value.value));
 list.appendChild(li);
 const btn = document.createElement('button');
 btn.className = 'btn btn-danger btn-sm float-right delete';
 btn.appendChild(document.createTextNode('X'));
 li.className = "list-group-item";
 li.appendChild(btn);
}

function deleteFields() {
 const value = document.querySelector('#item').value = '';
}

generate.addEventListener('click', (e) => {
  var items = document.querySelectorAll("#items li");
 
  var box= [];
  for (var j = 0; j < items.length; j++) {
    box.push(items[j].textContent);
  }
});

Im creating a list and appending a button to it. And i store all the li list that i have created to an array. however, the value of every list has an "X" as the last letter. How do i remove last text of every array element?

Denyyel
  • 11
  • 3
  • 1
    [JavaScript chop/slice/trim off last character in string](https://stackoverflow.com/questions/952924/javascript-chop-slice-trim-off-last-character-in-string) – Lawrence Cherone Dec 01 '20 at 00:56
  • Why put `btn.appendChild(document.createTextNode('X'));` there in the first place? – StackSlave Dec 01 '20 at 00:57
  • im appending a delete button to every list. create text node is the value of the delete button – Denyyel Dec 01 '20 at 01:09

2 Answers2

0

We can use substring to remove the last character from every element.

var box = [];
for (var j = 0; j < items.length; j++) {
  temp = items[j].textContent
  box.push(temp.substring(0, temp.length - 1));
}

The same thing can be done with slice.

var box = [];
for (var j = 0; j < items.length; j++) {
  temp = items[j].textContent
  box.push(temp.slice(0, -1));
}
0

you can use the substr() method on the string inside the loop

for (var j = 0; j < items.length; j++) {
    box.push(items[j].textContent.substr(0, items[j].textContent.length -1));
  }
Mostafa Hesham
  • 547
  • 4
  • 14