Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
Remove the URL of closest <a> element from list with JS

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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'))
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

do that this way, with event delegation

/* code for init list ( not accepted in SO snippet)
const
  list = JSON.parse( localStorage.getItem('list') || '[]')
, view = document.querySelector('ul#view')
  ;
*/
const
  list = ['www.go1.com', 'www.go2.com', 'www.go3.com', 'www.go4.com'] /* just for testing here */
, view = document.querySelector('ul#view')
  ;

// initial render
list.forEach(element =>
  {
  let LI = document.createElement('li');
  LI.innerHTML = `
      <a target='_blank' href='${element}'>${element}</a>
      <img src="images/remove.png" alt="Remove" width="12" height="12"> `
  view.appendChild(LI)
  })

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

  let 
    LI = event.target.closest('li')
  , iX = list.indexOf (LI.querySelector('a').textContent)
    ;
  list.splice(iX,1)
  view.removeChild(LI)
  // localStorage.setItem('list', JSON.stringify(list))

  console.log( JSON.stringify(list))  // just for snippet test
  setTimeout(console.clear,3000)     // just for snippet test
  })
<ul id="view"></ul>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!