user11815200
user11815200

Reputation:

remove element javascript with classename

  1. when I remove this with id it works but when I tried with className it didn't work
    const remov= document.createElement('a');
    remov.classList='clsx';
    remov.textContent='X';
    remov.setAttribute("id", "Div1");
    remov.onclick = function (){
    document.getElementById('Div1').remove();    }
  1. this is my code im trying to remove the element that i've created with id 'Div1' emphasized text
const lista = document.getElementById('list');

eventlisteners();

function eventlisteners(){
  document.querySelector('#form').addEventListener('submit', yrlist);
}

//function

function yrlist(e){

    e.preventDefault();  
    var textare =document.getElementById('textar').value;


    const li= document.createElement('li');
    li.textContent=textare;
    li.classList='clsli';
    li.setAttribute("id", "Div1");

    const remov= document.createElement('a');
    remov.classList='clsx';
    remov.textContent='X';
    remov.setAttribute("id", "Div1");
    remov.onclick = function (){
      document.getElementById('Div1').remove();
    }

    li.appendChild(remov);

    lista.appendChild(li);

}

Upvotes: 0

Views: 63

Answers (2)

enhzflep
enhzflep

Reputation: 13089

remov.classList = 'clasx'; is just wrong. The classList member is actually a DOMTokenList, not a string. As such, it has functions of it's own. Rather than trying to set this member, you need to use the add function it contains.

I.e remov.classList.add('clsx');

It seems that clicking on the element will have the effect of removing it. This is functionality you've given it at creation time. There's a better way to go about this. Rather than trying to find the element, (which must be identifiable in some manner) why not just have the element remove itself? If you connect the action and the event using AddEventListener, rather than by overwriting a member of the element yourself, a neat thing happens - the function that gets called behaves as though it was a part of the element that triggered it, and so the this keyword refers to itself. It's a huge help, but for the uninitiated, can be a real headache.

const removeMe = document.createElement('a');
removeMe.classList.add('clsx');
removeMe.textContent = 'X';
removeMe.addEventListener('click', function(evt){ this.remove(); }, false);
li.appendChild(removeMe);

Upvotes: 0

emtei
emtei

Reputation: 631

Note that getElementById returns single element while getElementsByClassName returns list of elements. So you need to iterate through this list. And remove each element.

For example you can do this using loop:

const elements = document.getElementsByClassName("clsx");
for(var x=0; x < elements.length; x++) {
    elements[x].remove();
}

Upvotes: 1

Related Questions