Home > Enterprise >  Removing selected child from an div element
Removing selected child from an div element

Time:01-28

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?

//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()]);
}

CodePudding user response:

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>

CodePudding user response:

2 solutions:

//html part
<div contenteditable="true" id="editableField">
  <li>Apple</li>
  <li>Orange</li>
  <li>Banana</li>
  <li>potato</li>
  <li>grape</li>
  <li>egg</li>
  <li>milk</li>
</div>
<input type="text"  />
<button >Delete</button>

<script>
  const myDiv = document.querySelector("#editableField");
  const input = document.querySelector(".input");
  const btn = document.querySelector(".button");

  // first way thanks to event bubbling
  myDiv.addEventListener("click", (ev) => {
    ev.target.remove();
  });

  // second way, by iterating through items
  btn.addEventListener("click", () => {
    // The "onclick="..." in the html is old solution, new and better is addEventListener(...)"
    const myDivChildren = [...myDiv.children]; // The "..." is spread operator, "myDiv" is HTMLCollection, an array like object in orter ot iterate ovet it I created array by spreading it
    const inputValue = input.value || myDivChildren.length - 1; // take input value if exist, if not then last index so remove last item

    myDivChildren.forEach((el, i) => {
      if (i == inputValue) {
        el.remove(); // When indexes match then delete
      }
      return; // When indexes match then stop executing loop
    });

    input.value = "";
  });

I got rid of getSelection(), it complicates removing items, do you care about using getSelection()? Should I use it in the answer?

  • Related