简体   繁体   中英

Cannot seem to work out how to remove childNodes properly

So I have build a little display. If you click on a filter word it is supposed to display a tag. Thats working so far. Thats the first code snippet.

But If I click on the filter word I want it to be removed from the document again and I cant figure that out. That would be the second function. I want to iterate thorugh the created "display" elements and remove them again if they contain the "clicked value" area. The out commented stuff did not work I either get the error that leng is not a function or that he "cannot read property 0 of undefined at tagFunction".

Thank you for your help !

 var area = event.target.textContent; var spa = document.createElement("span"); var p = document.createElement("p"); spa.setAttribute('class', 'display'); p.setAttribute("class", "display1") var text = document.createTextNode(area); spa.appendChild(p); p.appendChild(text); p.addEventListener("click", tagFunction); document.getElementById("tags123").appendChild(spa);
 <div class="tags123" id="tags123"> </div>

 function tagFunction() { var area = event.target.textContent; var leng = document.getElementsByClassName("display1"); var tags123 =document.getElementsByClassName("tags123"); for(var ll = 0;ll<leng.length;ll++){ if(leng[ll].innerText.trim().contains(area)){ //tags123.removeChild(leng(ll)); tags123.children[ll].remove(); // leng(ll).remove(); } } }

This was the error. I had to declare parentNode of the leng[ll] element first.

             if(leng[ll].innerText.trim().contains(bereich)){
                 var vader = leng[ll].parentNode;
                 document.getElementById("tags123").removeChild(vader);

There are two error in two lines:

if(leng[ll].innerText.trim().includes(area)){ //should be contains and not includes

leng(ll).remove(); // should be [ ] and not ( )

it will be like this:

if(leng[ll].innerText.trim().contains(area)){

leng[ll].remove();

 var area = "text test"; var spa = document.createElement("span"); var p = document.createElement("p"); spa.setAttribute('class', 'display'); p.setAttribute("class", "display1") var text = document.createTextNode(area); spa.appendChild(p); p.appendChild(text); p.addEventListener("click", tagFunction); document.getElementById("tags123").appendChild(spa); function tagFunction() { var area = event.target.textContent; var leng = document.getElementsByClassName("display1"); var tags123 =document.getElementsByClassName("tags123"); console.log(leng); for(var ll = 0; ll <= leng.length; ll++){ if(leng[ll].innerText.trim().includes(area)){ leng[ll].remove(); } } }
 <div class="tags123" id="tags123"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM