Reputation:
const remov= document.createElement('a');
remov.classList='clsx';
remov.textContent='X';
remov.setAttribute("id", "Div1");
remov.onclick = function (){
document.getElementById('Div1').remove(); }
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
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
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