I tried to make a code to remove a li from ul but I would like to be more specific. I would like to find exact anchor link before removing it along with the li it contains.
In the example below, I want to remove only Another link.
My code so far looks like:
<ul class="working-list">
<li class="work color1">
<a href="?c=Some link 1">
<span class="title">
link 1</span>
</a>
</li>
<li class="work color1">
<a href="?c=someLink2"><span class="title">
Some link 2</span>
</a>
</li>
<li class="work color1">
<a href="?c=anotherLink"><span class="title">
Another link</span>
</a>
</li>
<li class="work color1">
<a href="?c=SmallLink"><span class="title">
Small link</span>
</a>
</li>
</ul>
And the script so far:
let pickEl = document.querySelectorAll('.working-list li');
// let pickA = document.querySelector('a[href=\'?c=anotherLink\']');
console.log(pickEl);
pickEl[3].remove();
What would be the best approach?
You can try using Attribute selectors selector:
let pickEl = document.querySelector('.working-list li a[href="?c=anotherLink"]');
console.log(pickEl);
//remove the parent li
pickEl.closest('li').remove();
<ul class="working-list">
<li class="work color1">
<a href="?c=Some link 1">
<span class="title">link 1</span>
</a>
</li>
<li class="work color1">
<a href="?c=someLink2">
<span class="title">Some link 2</span>
</a>
</li>
<li class="work color1">
<a href="?c=anotherLink">
<span class="title">Another link</span>
</a>
</li>
<li class="work color1">
<a href="?c=SmallLink">
<span class="title">Small link</span>
</a>
</li>
</ul>
You can forEach the pickEl then see textContent like:
let pickEl = document.querySelectorAll('.working-list li');
const deleteText = 'Another link';
pickEl.forEach(el =>{
const a = el.querySelector('a');
if(a.textContent.trim() === deleteText){
el.remove();
}
});
<ul class="working-list">
<li class="work color1">
<a href="?c=Some link 1">
<span class="title">
link 1</span>
</a>
</li>
<li class="work color1">
<a href="?c=someLink2"><span class="title">
Some link 2</span>
</a>
</li>
<li class="work color1">
<a href="?c=anotherLink"><span class="title">
Another link</span>
</a>
</li>
<li class="work color1">
<a href="?c=SmallLink"><span class="title">
Small link</span>
</a>
</li>
</ul>