Search code examples
javascriptdomremovechildappendchildcreateelement

How to remove next element using JavaScript (without using jQuery)


I need something like this.

<a onclick="SaveNote(this);" >Save</a>
<a href="javascript:void(0);" id="112">Cancel</a>
<a href="javascript:void(0);" id="112">Delete</a>

If I click on the Save anchor , I want to remove all three anchor elements as shown above, without using any id, and replace them with an Edit anchor. I currently have some Javascript code that looks something like this :

function SaveNote(e){
   e.nextSibling.removeNode;
   e.nextSibling.removeNode;
   e.nextSibling.removeNode;
}

Have you any idea regarding this issue?


Solution

  • You could do something like this

    HTML

    <div>Stuff before</div>
    <div>
        <a id="save" href="#">Save</a>
        <a id="cancel" href="#">Cancel</a>
        <a id="delete" href="#">Delete</a>
    </div>
    <div>Stuff after</div>
    

    Javascript

    function emptyNode(node) {
        while (node.firstChild) {
            node.removeChild(node.firstChild);
        }
    }
    
    function saveNote(e) {
        var parent = e.target.parentNode,
            edit = document.createElement("a");
    
        emptyNode(parent);
    
        edit.id = "edit";
        edit.href = "#";
        edit.appendChild(document.createTextNode("Edit"));
        parent.appendChild(edit);
    }
    
    document.getElementById("save").addEventListener("click", saveNote, false);
    

    On jsfiddle

    Note: this requires support of addEventListener which is easily dealt with