Search code examples
javascriptremovechild

Remove multiple elements with same name using removeChild?


I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function?

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


Solution

  • 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);
        }
    }