Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing selected child from an div element

My question aims to find the simplest way for removing a child from a div element. In this case either Apple, Orange or Banana. Which means you can put the cursor on one of these words and then click delete child.

The only way Iam thinking is doing it in two steps:

  • Returning the index of the selected child with returnIndexOfChild() (custom built)
  • Using the removeChild method

I mean when you are having a big text java script engine has to loop through the whole text to find the index. Is there a more direct way like deleting anchorNode by selection object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//html part
<div contentEditable="true" id="editableField"><b>Apple</b><i>Orange</i><b>Banana</b></div>
<button onclick="deleteChild()"> Delete</button>

//javascript part
var selection = document.getSelection();
myDiv = document.getElementById("editableField");

//Returns index of selected child (1)
function returnIndexOfChild(){
        let i = 0;
        for (i; i < myDiv.childNodes.length; i++){
                if(selection.anchorNode.parentElement === myDiv.childNodes[i]){
                        console.log(i);
                        break;
                };
        }
return i;
}

//Removing Child(2)
function deleteChild (){
 myDiv.removeChild(myDiv.childNodes[returnIndexOfChild()]);
}

>Solution :

You can just call remove() on the element itself

function deleteChild (){
  const selection = document.getSelection();
  selection.anchorNode?.parentElement?.remove();
}
<div contentEditable="true" id="editableField"><b>Apple</b><i>Orange</i><b>Banana</b></div>
<button onclick="deleteChild()"> Delete</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading