1/24/11

Working with DOM , nodes and Objects (part 2) : Deleting Nodes

As my last post of DOM was on Adding nodes here is a post that will help you in deleting the last entered node. ie DELETING Nodes.



*----------------------*----------------------*---------------------*


HTML CODE:


<html>
<head>
    <title>Deleting Nodes</title>
    <script type="text/javascript" src="script.js">
    </script>
</head>
<body>
    <form action="#">
        <p><textarea id="textArea" rows="5" cols="30"></textarea></p>
        <input type="submit" value="Add some text to the page" />
    </form>
    <a id="deleteNode" href="#">Delete last paragraph</a>
</body>
</html> 
 
The Above is the HTML code. After this the javascript code is there that will help you in detecting whether any nodes is present for deletion or not.

*----------------------*----------------------*---------------------*

script.js:


window.onload = initAll;

function initAll() {
    document.getElementsByTagName("form")[0].onsubmit = addNode;
    document.getElementById("deleteNode").onclick = delNode;
}

function addNode() {
    var inText = document.getElementById("textArea").value;
    var newText = document.createTextNode(inText);

    var newGraf = document.createElement("p");
    newGraf.appendChild(newText);

    var docBody = document.getElementsByTagName("body")[0];
    docBody.appendChild(newGraf);

    return false;
}

function delNode() {
    var allGrafs = document.getElementsByTagName("p");
    
    if (allGrafs.length > 1) {
        var lastGraf = allGrafs.item(allGrafs.length-1);
        var docBody = document.getElementsByTagName("body")[0];
        var removed = docBody.removeChild(lastGraf);
    }
    else {
        alert("Nothing to remove!");
    }

    return false;
} 
 
After u have entered the Code it will look like this:

Before Deletion
After Deleting I


When Nothing to remove, It gives an ALERT......

SHARE THIS POST: