Home > Enterprise >  Remove the URL of closest <a> element from list with JS
Remove the URL of closest <a> element from list with JS

Time:10-01

So I have a list of urls and I have remove button(img button). When clicked to remove button. The url which is next to button must be removed from the list.

let   list   = [];
const remove = document.getElementById('remove')
const view = document.getElementById('view');
const saveInput = document.getElementById('save-input');

saveInput.addEventListener('click', function (){
    list.push(input.value);
    input.value = '';
    localStorage.setItem('list', JSON.stringify(list));
    render(list);
})

remove.addEventListener('click', function (){
  remove.closest("li").remove();
  render(list);
  })
   
function render(lst) {
  let listItems = '';  
  lst.forEach(element => {
    listItems  = `
      <li>
        <a target='_blank' href='${element}'>${element}</a>
        <img src="images/remove.png" 
           onClick="remove_item(this)" 
           id="remove" alt="Remove" width="12" height="12"> 
     </li>`
    });
  view.innerHTML = listItems;
}

I am printing the items to screen by using render() function. And my list looks like this.

enter image description here

Since url is not removed from list by removing closest <li> when render() function ran again; item comes back!

So when clicked to bin image; the link next to it must be removed from the list. Thank you!

CodePudding user response:

I guess you want something like this https://jsfiddle.net/er2uj8pL/

Better to remove item from list and render it again (I assumed you are using jquery based on .closest)

const remove = document.getElementById('remove')

const lst = ['item1', 'item2'];


remove_item = function(index) {
    lst.splice(index, 1)
  render(document.getElementById('view'));
}
   
function render(view) {
  let listItems = '';  
  lst.forEach((element, index) => {
    listItems  = `
      <li>
        <a target='_blank' href='${element}'>${element}</a>
        <img src="images/remove.png" 
           onClick="remove_item(${index})" 
           id="remove" alt="Remove" width="12" height="12"> 
     </li>`
    });
  view.innerHTML = listItems;
}


render(document.getElementById('view'))

CodePudding user response:

Your using Id selector getElementById You should use class when there morethen one element with same identity

const remove = document.getElementByClass('remove')


function render(lst) {
  let listItems = '';  
  lst.forEach(element => {
    listItems  = `
      <li>
        <a target='_blank' href='${element}'>${element}</a>
        <img src="images/remove.png" 
           onClick="remove_item(this)" 
           class="remove" alt="Remove" width="12" height="12"> // here change
     </li>`
    });
  view.innerHTML = listItems;
}

CodePudding user response:

do that this way, with event delegation

list element is not needed

view.addEventListener('click', function (event)
  {
  if (!event.target.matches('img[alt="Remove"]')) return

  let eLI = event.target.closest('li')
  view.removeChild(eLI)
  })
   
function render(lst)
  {
  lst.forEach(element =>
    {
    let eLI = document.createElement('li')
    eLI.innerHTML = `
        <a target='_blank' href='${element}'>${element}</a>
        <img src="images/remove.png" alt="Remove" width="12" height="12"> `
    })
  view.appendChild(eLi)
  }

CodePudding user response:

You have duplicate IDs that is not allowed

I would delegate and splice

My code allows you to sort the list

const view = document.getElementById("view");
let list = ["el1", "el2"];
const remove = document.getElementById('remove')

view.addEventListener('click', function(e) {
  const tgt = e.target;
  if (tgt.matches("img.remove")) {
    const removeElement = tgt.dataset.element;
    const idx = list.findIndex(elem => elem === removeElement);
    list.splice(idx, 1)
    render(list);
  }
})

function render(lst) {
  view.innerHTML = lst.map((element, i) => `<li>
        <a target='_blank' href='${element}'>${element}</a>
        <img src="images/remove.png" data-element="${element}"          
           class="remove" alt="Remove" width="12" height="12"> 
     </li>`).join("")
}
render(list)
<ul id="view"></ul>

CodePudding user response:

I've here a simple solution with Vanilla JS:

const remove = document.querySelectorAll('.remove')

remove.forEach((element) => {
  element.addEventListener('click', event => {
    const link = event.target.previousElementSibling
    const parentElement = event.target.parentNode
    console.log('Link to be removed:', link)
    
    parentElement.remove()
    console.log('List item removed!')
  })
})
ul { list-style: none }
li { display: flex; }
a { margin-right: 20px; }
<ul class="list">
    <li>
      <a href="https://site-1.com">https://site-1.com</a>
      <button class="remove">           
  • Related