Wednesday, 4 July 2012

Javascript adding and deleting node..

Adding and deleting node in javascript is pretty simple. You don't need to use jquery or any other library to accomplish such small tasks like this. See the example below.

I am using a textarea, submit button and an anchor tag to add and delete node through javascript.

Click here to see the working example. http://jsfiddle.net/coolvin21/QUUtk/

<html>
    <head>
        
<script type="text/javascript">
            window.onload = initAll; // CALLING FUNCTION ON WINDOW ONLOAD      
            function initAll(){
                document.getElementsByTagName("form")[0].onsubmit=submitfunc; // FUNCTION ON PRESS OF SUBMIT BUTTON
                document.getElementById("removePara").onclick=removePara; //FUNCTION ON CLICK ON ANCHOR
            };
          
            function submitfunc(){
                var tAareaVal = document.getElementById("tAreaId").value;
                var txtNode = document.createTextNode(tAareaVal); //TEXT NODE OF TEXT AREA VALUE
              
                var pElement = document.createElement("p");
                pElement.appendChild(txtNode); //INSERTING TEXTNODE IN PARAGRAPH TAG
              
                var bodyDoc = document.getElementsByTagName("body")[0];
                bodyDoc.appendChild(pElement); //WRITING INSIDE BODY TAG
              
                return false;
            };
          
            function removePara(){              
                var allGrafs = document.getElementsByTagName("p");
              
                if(allGrafs.length>=1){
                    var lastGraf = allGrafs.item(allGrafs.length-1); //LAST PARAGRAPH WOULD BE ALL PARAGRAPH-1
                    var bodyDoc = document.getElementsByTagName("body")[0];
                    var removed = bodyDoc.removeChild(lastGraf); //DELETING LAST PARA
                }
                else{
                    alert("No ParaGraph Added")
                }
            }          
        </script>
    </head>
    <body>
        <form id="formId">
            <textarea id="tAreaId" cols="30" rows="5">Please type here to add Paragraph</textarea><br />
            <input type="submit" value="CLICK HERE TO ADD PARAGRAPH">
        </form>
        <br /><br /><a href="#" id="removePara">CLICK HERE TO REMOVE PARAGRAPH</a>
    </body>
</html>​​​​​​​​​​​​​​​​​​​​​​​​​

No comments:

Post a Comment