Learner33
Learner33

Reputation: 131

Remove specific list item from DOM using Javascript

I have the following unordered list in my DOM. I am currently searching for a method, that can delete a specific list item using Javascript.

<ul class="list">
  <li id="1">Depy</li>
  <li id="2">HI</li>
  <li id="3">WA</li>
  <li id="4">FA</li>
</ul>

I am creating a function in JS, which accepts a string argument. For example "FA" and then it is supposed to delete find and delete list items containing string in their content.

To Sum up I want to delete by specific list element by if it has a matched string in content.

Upvotes: 1

Views: 1875

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44105

Make an array of li elements, then iterate through them and delete the item with the correct content:

function removeListItemByText(text) {
  const li = [...document.querySelectorAll("li")];
  li.forEach(elem => {
    if (elem.innerText == text) elem.parentNode.removeChild(elem);
  });
}

document.getElementById("button").onclick = function() {
  removeListItemByText("FA");
};
<ul class="list">
  <li id="1">Depy</li>
  <li id="2">HI</li>
  <li id="3">WA</li>
  <li id="4">FA</li>
</ul>

<button id="button">Remove FA</button>

Upvotes: 2

Related Questions