1

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.

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Jack Bashford in my case it was innerText not innerHTML but appreciate it ;)
No worries @Learner33 - fixed answer too ;)
@JackBashford why is this part in square brackets with dots at the beginning? [...document.querySelectorAll("li")]; Surely document.querySelectorAll('li"); will work just as it is?
document.querySelectorAll('li') returns a NodeList - the [...] is spread notation and converts it into an array so I can use forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.