javascript remove li without removing ul?
Asked Answered
M

7

30

Is there any way to remove the li elements of a ul without also removing the ul? I can only seem to find this.

var element = document.getElementById('myList');
element.parentNode.removeChild(element);

But, this removes the ul. I'm hoping to be able to remove and append li elements on the fly without also having to createElement the ul every time I remove li elements. Just looking for a simpler way. Thanks for any help.

<div id="listView">
  <ul id="myList" class="myList-class">
    <li>item 1</li>
    <li>item 2</li>
  </ul>
</div>
Mars answered 13/9, 2013 at 20:50 Comment(10)
You have an li with id="div"?Wychelm
@Jeffman Keeps the next developer guessing.Newsmagazine
Sorry, was in a hurry. html posted.Mars
Cough. So is it div or myDiv?Wychelm
Wow, now that you actually posted your code, @Jeffman was right! Just so you know, giving a ul an id of myDiv is a very bad idea. Even myUL isn't great, try to make it descriptive, not deliberately confusing.Belgravia
omg! it's a id. no div.Mars
'#id' looks pretty wrong, and doesn't match the HTML. Are you trying to mix jQuery into this?Wychelm
Yeah. I agree on everything you guys are saying. The id's and class names should be better. They are not the real names. I just used placeholder names for the purpose of the question. The original post was bunk. Sorry for that.Mars
The code you have now DOES target the ul, so not what you want. To remove an li you need a reference to it. You get that by id or index number in some sort of collection. The answers below work if you want all the lis removed. If you want to target just one, you'll need to specify it more clearly, by index, content, attribute -- something.Wychelm
I know this removes the ul. I don't want to do that. I want to remove all li elements within the ul, while preserving the ul. What about Justin's method? Is this a proper way to handle? It seems pretty straight-forward and direct.Mars
D
33

You can do something like this.

var myList = document.getElementById('myList');
myList.innerHTML = '';

If you are using jQuery

$('#myList').empty();

Both of these will remove EVERYTHING inside the list.

Detector answered 13/9, 2013 at 20:54 Comment(0)
O
17

This should do the trick:

var lis = document.querySelectorAll('#myList li');
for(var i=0; li=lis[i]; i++) {
    li.parentNode.removeChild(li);
}

Demo http://jsfiddle.net/krasimir/UhhuX/

Oxazine answered 13/9, 2013 at 21:0 Comment(2)
This worked for me with one addition. Because I was only removing certain list objects, not all of them I had to add "i = i -1;" after the removeChild call to make sure the list and the i index stayed in sync.Dochandorrach
I liked this answer because it only removes the <li> elements. If, for some reason, you have something else in your <ul>, that won't get wiped out.Moffit
P
9

The reason it's removing the ul is because you have the element variable pointing to the ul. Your next line of code then moves up to the parent (#listView) and applies the removechild method with the element variable (which points to ul element) passed to it.

If you need to remove all the li elements then you can use:

document.getElementById('myList').innerHTML = '';

which will empty the ul completely. If you need to remove selected li elements then you can traverse from #myList to the particular child elements using something like:

var ulElem = document.getElementById('myList');

ulElem.removeChild(ulElem.childNodes[i])

where i is the index of the li you want to remove (0 for 1st, 1 for 2nd, etc.)

For reference: https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild

Poppy answered 13/9, 2013 at 21:7 Comment(0)
G
1
const li = document.querySelectorAll(".list-item-class");
for(let i = 0; i <= li.length; i++ ){
    l = li[i];
    l.remove();
}
Geronimo answered 18/3, 2021 at 23:5 Comment(0)
D
0

As long as we have a first child - remove it. (which will be as long as we have even one member).

  const removeNodesFromList = () => {
    const nodes = document.querySelector('.ul-class-selector');
    while (nodes.firstChild) {
      nodes.removeChild(nodes.firstChild);
    }
  };
Dumdum answered 30/11, 2017 at 12:26 Comment(0)
S
0

let ol = document.querySelector("ol");

function addItem() {
  let lastIndex = ol.childElementCount;
  let li = document.createElement("li");
  li.dataset.index = lastIndex;
  let a = document.createElement("a");
  a.href = "#";
  a.innerHTML = " Remove";
  a.addEventListener("click", function(e) {
    e.preventDefault();
    let index = e.target.parentNode.dataset.index;
    removeItem(parseInt(index));
  })
  li.appendChild(a);
  ol.appendChild(li);
}

function removeItem(i) {
  let li = ol.children[parseInt(i)];
  ol.removeChild(li);
  for (let j = i; j < ol.childElementCount; j++) {
    let li = ol.children[j];
    li.dataset.index = j;
  }
}

addItem();
<ol>
</ol>
<button onclick="addItem()">Add</button>
Semanteme answered 5/10, 2021 at 10:29 Comment(1)
While your snippet may be useful, please re-read the question, the user asks how to remove all nodes contained in a <ul> element.Underhand
M
0

The way I solve this problem is that. I create the deletion feature within the creation function:

HTML

<body>
    <div class="myclass">
        <h1>TODO App</h1>
        <!-- user input -->
        <input class="user_input" type="mytext" name="mytext" placeholder="Enter text">
        <button class="mybutton">Add</button>
    </div>
    <div>
        <ul class="ul-container"></ul>
    </div>
</body>

JavaScript

function creation() {
    const userInput = document.querySelector(".user_input").value;
    const ulContianer = document.querySelector(".ul-container");

    console.log(userInput);
    if (userInput !== "") {
        let li = document.createElement("li");
        let test = document.createTextNode(userInput);
        li.append(test);
        li.addEventListener('click', function (e) {
            li.parentNode.removeChild(li);
        })
        ulContianer.appendChild(li);
        document.querySelector(".user_input").value = "";
    }
}

So after you create it. Once you click li element, it will gone.

Mikamikado answered 19/11, 2021 at 3:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.