javascript 从div元素中移除选定子元素

jobtbby3  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(234)

我的问题旨在找到从div元素中删除子元素的最简单方法。在本例中,可以是Apple、橙子或Banana。这意味着您可以将光标放在其中一个单词上,然后单击delete child。
我想的唯一办法是分两步走:

  • 使用returnIndexOfChild()返回所选子级的索引(自定义构建)
  • 使用removeChild方法

我的意思是当你有一个大的文本java脚本引擎必须循环通过整个文本找到索引。有没有更直接的方法,如删除锚节点的选择对象?

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

qhhrdooz1#

您可以只对元素本身调用remove()

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>
wlsrxk51

wlsrxk512#

2种解决方案:

//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" class="input" />
<button class="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 = "";
  });

我去掉了getSelection(),它使删除项目变得复杂,你关心使用getSelection()吗?我应该在答案中使用它吗?

相关问题