Remove multiple elements with same name using removeChild?

十年热恋 提交于 2019-12-25 01:09:06

问题


I have an elements with multiple elements inside. The elements inside all have the same name. Is there away to have a function remove all of them?

(refer to this question for example Remove multiple children from parent?


回答1:


Here's a solution that removes the first level children with the specified name for the parent with the specified id. If you want to go deeper, you can recursively call it on the child elements you get inside (you'll have to add a parent parameter as well).

function removeChildren (params){
    var parentId = params.parentId;
    var childName = params.childName;

    var childNodes = document.getElementById(parentId).childNodes;
    for(var i=childNodes.length-1;i >= 0;i--){
        var childNode = childNodes[i];
        if(childNode.name == 'foo'){
            childNode.parentNode.removeChild(childNode);
        }
    }
}

And to call it:

removeChildren({parentId:'div1',childName:'foo'});

And a fiddle for testing:

Notes: You can only access the name element dependably in JavaScript when it supported on your element (e.g. NOT on DIVs!). See here for why.

UPDATE:

Here's a solution using className based on our conversation:

function removeChildren (params){
    var parentId = params.parentId;
    var childName = params.childName;

    var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo');
    for(var i=childNodesToRemove.length-1;i >= 0;i--){
        var childNode = childNodesToRemove[i];
        childNode.parentNode.removeChild(childNode);
    }
}



回答2:


ok this should be easy. First get the parent element:

var theParent = document.getElementById("notSoHappyFather");

then get an array of the nodes that you want to remove:

var theChildren = theParent.getElementsByName("unluckyChild");

Lastly, remove them with a loop:

for (var i = 0; i < theChildren.length; i++)
{
  theParent.removeChild(theChildren[i]);
}



回答3:


A sample of your HTML would get you a more complete answer, but one can fairly easy call DOM functions to get the list of children and just remove them. In jQuery, remove all children would be something like this:

$("#target > *").remove();

or

 $("#target").html("");

And, you can see a demo here: http://jsfiddle.net/jfriend00/ZBYCh/

Or, not using jQuery you could also do:

document.getElementById("target").innerHTML = "";

If you're trying to only remove a subset of the children (and leave others intact), then you need to be more specific how one would determine which children to leave and which to remove. In jQuery, you could use a .find() select or a filter() selector to narrow the list of children to just the children you wanted to target for removal.



来源:https://stackoverflow.com/questions/6795585/remove-multiple-elements-with-same-name-using-removechild

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!