Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to dynamically remove/delete elements via JavaScript

March 26th, 2008  |  Published in javascript  |  25 Comments


This post is in response to one of the comments on have received regarding the removal of elements via JavaScript. I have taken the original function posted and edited it a little bit for the demo.

Demo
I am the parent div.

I am a child div within the parent div.

 


Here is the plain HTML code:

1
2
3
4
5
6
7
8
<div id="parent" style="border: 1px solid red; padding: 10px;">
     I am the parent div.
     <div id="child" style="border: 1px solid green; padding: 10px;">
           I am a child div within the parent div.
     </div>
</div>
<p>&nbsp;</p>
<input type="button" value="Remove Element" onClick="removeElement('parent','child');">

The important thing to note here is that the child div is within the parent div. Once the Remove Element button is clicked, the onClick event listener is triggered and launches the removeElement JavaScript function. This functions accepts two arguments:

  • parent – This is just the div id of the parent div.
  • child – This is the div id of the child div.

Here is the code for the removeElement JavaScript function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function removeElement(parentDiv, childDiv){
     if (childDiv == parentDiv) {
          alert("The parent div cannot be removed.");
     }
     else if (document.getElementById(childDiv)) {     
          var child = document.getElementById(childDiv);
          var parent = document.getElementById(parentDiv);
          parent.removeChild(child);
     }
     else {
          alert("Child div has already been removed or does not exist.");
          return false;
     }
}

The if block in lines 2-6 attempts to obtain the child element if it exists. This is just in case the user has already removed the child div and is reattempting to it. In this case, a JavaScript error would normally pop up because the child div does not exist.

If the child element does exist, the first thing that we do is obtain the child element in line 3 using the child div id. Next, we do the same thing with the parent element by using the parent div id Lastly, we invoke the removeChild method from the parent element and pass the child element as the argument. That’s it!

If the child div has already been removed, the else block in lines 7-10 gets executed. In this case, an alert would tell the user that the child div has already been removed and the function would return a false value.

Here is another demo of this JavaScript function where you can type in the name of the child element to be removed and just click on the Remove Element button OR you can just click the button that corresponds to each given child div to remove it.

Demo
My name is parentDiv. I cannot be removed.

My name is child1.
My name is child2.
My name is child3.

 

Name of child element to be removed:

For those who are lazy in typing in the actual names, we have these handy-dandy buttons:

We are using the same JavaScript function as above. Here is the plain HTML for the demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div id="parentDiv" style="border: 1px solid red; padding: 10px;">
     My name is <b>parentDiv</b>.  I cannot be removed.
     <div id="child1" style="border: 1px solid green; padding: 10px; margin: 10px;">
          My name is <b>child1</b>.
     </div>
     <div id="child2" style="border: 1px solid blue; padding: 10px; margin: 10px;">
          My name is <b>child2</b>.
     </div>
     <div id="child3" style="border: 1px solid purple; padding: 10px; margin: 10px;">
          My name is <b>child3</b>.
     </div>
</div>
<p>&nbsp;</p>
Name of child element to be removed: <input id="nameOfChild" type="text" value="child2"><input type="button" value="Remove Element" onClick="var name=document.getElementById('nameOfChild').value; removeElement('parentDiv', name);">
<br><br>
For those who are lazy in typing in the actual names, we have these handy-dandy buttons:
<input type="button" value="Remove child1" onClick="removeElement('parentDiv', 'child1');">
<input type="button" value="Remove child2" onClick="removeElement('parentDiv', 'child2');">
<input type="button" value="Remove child3" onClick="removeElement('parentDiv', 'child3');">
<input type="button" value="Remove parentDiv" onClick="removeElement('parentDiv', 'parentDiv');">

Here is a demo that removes child elements from the parent using checkboxes that a user would select. This demo uses the same removeElement JavaScript function.

Demo
My name is parentDivElement. I cannot be removed.

My name is childOne.
My name is childTwo.
My name is childThree.

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div id="parentDivElement" style="border: 1px solid red; padding: 10px;">
     My name is <b>parentDivElement</b>.  I cannot be removed.
     <div id="childOne" style="border: 1px solid green; padding: 10px; margin: 10px;">
          My name is <b>childOne</b>.
     </div>
     <div id="childTwo" style="border: 1px solid blue; padding: 10px; margin: 10px;">
          My name is <b>childTwo</b>.
     </div>
     <div id="childThree" style="border: 1px solid purple; padding: 10px; margin: 10px;">
          My name is <b>childThree</b>.
     </div>
</div>
<p>&nbsp;</p>
<input id="cb1" type="checkbox" value="childOne" onClick="removeElement('parentDivElement', this.value);"><label for="cb1">Remove <b>childOne</b></label>
<input id="cb2" type="checkbox" value="childTwo" onClick="removeElement('parentDivElement', this.value);"><label for="cb2">Remove <b>childTwo</b></label>
<input id="cb3" type="checkbox" value="childThree" onClick="removeElement('parentDivElement', this.value);"><label for="cb3">Remove <b>childThree</b></label>

The concept is the same as the previous demos where we attach the removeElement function to an event handler, which in this case is the onClick event handler of the checkbox. Once the checkbox is checked (or even unchecked), it fires off the onClick event handler and executes the removeElement JavaScript function and passes off the name of the parent div and the value of the checkbox.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Responses

Feed Trackback Address
  1. Justin says:

    June 17th, 2008 at 8:16 pm (#)

    If there are multiple child elements in the parent, all of them are removed. Is there a way that I can make this so that only one is removed?

    [Reply]

  2. Knix says:

    June 18th, 2008 at 7:20 am (#)

    Hi Justin,

    Please look at the 2nd demo on this page where I have 3 child elements within 1 parent. Each child is given a specific id that you can refer to when using the getElementById method to retrieve the specific DOM object.

    [Reply]

    Charles reply on August 11th, 2008 6:19 pm:

    What if the Child is programmatically created? What is it’s div ID then? This is the part i’m having the most trouble with. I’m dynamically creating an Input inside a div. Along with this, I’m creating a button to remove the entire div..except, I don’t know what to ID to pass into the removeElement function…

    I’ve pasted it in pastebin: http://pastebin.com/m1cf0ba22

    It’s the first highlighted line. You responded in your other article about dynamic creation that the ID was already available but I’m just not making the logical gap.

    Any thoughts would be greatly appreciated.

    [Reply]

    Knix reply on August 12th, 2008 11:09 pm:

    Hi Charles,

    I think the problem is that you did not indicate an ID for the created child element. Once you place the ID in there, which is created dynamically using the counter variable, you can also use that same ID for the input button that is used for removing it.

    http://pastebin.com/m60464aaa

    I have not tested it but I hope the basic idea is there.

    [Reply]

    Knix reply on August 13th, 2008 8:24 am:

    Hi Charles,

    I noticed a mistake in my edit and edited the link. Please refer to the new link.

    Thanks.

  3. shammim says:

    July 2nd, 2008 at 4:08 am (#)

    I want that a “Remove” button to be created alongside newly created element. So when I’ll click the remove button, that particular element (along with the remove button related with it) will be removed. Is this possible?

    [Reply]

    Knix reply on July 2nd, 2008 9:18 am:

    Hi shammim,

    Here is an example of your request:

    Parent of Block

    Block

    A DIV element within Block
     

    HTML code:

    1
    2
    3
    4
    5
    6
    7
    
    <div id='parentOfBlock' style='padding: 10px; border: 1px solid purple;'>Parent of Block
       <div id='block' style='border: 1px solid blue; padding: 10px;'>Block
          <div style='border: 1px solid green;float: left;'>A DIV element within Block</div>
          <input style='float: right;' type='button' value='Remove Block' name='Remove entire block' onClick='removeElement("parentOfBlock", "block")'>
          <div style='clear: both;'>&nbsp;</div>
       </div>
    </div>

    I hope this helps.

    [Reply]

    shamim reply on July 3rd, 2008 5:03 pm:

    Thank you very very much

    [Reply]

  4. Munish Pathak says:

    September 25th, 2008 at 2:59 am (#)

    It was really good, when I tried it.

    [Reply]

  5. Dooza says:

    October 22nd, 2008 at 5:55 am (#)

    I am trying to have a add and remove button after each form field that is added. When the buttons aren’t generated by the javascript it works, but when they are, they don’t work.

    My problem is that I don’t know what to replace single quoutes with. I can see that double quotes get replaced with a single quote, but what about single quotes? Any help would be really appreciated.

    Here is my code:

    var counter = 1;
    var limit = 10;
    function addInput(divName){
    if (counter == limit) {
    alert(“You have reached the limit of adding ” + counter + ” inputs”);
    }
    else {
    var newdiv = document.createElement(‘div’);
    newdiv.setAttribute(‘id’,'email’ + (counter + 1));
    newdiv.innerHTML = “Email ” + (counter + 1) + ” “;
    document.getElementById(divName).appendChild(newdiv);
    counter++;
    }
    }
    function removeElement(parentDiv, childDiv){
    if (childDiv == parentDiv) {
    alert(“The parent div cannot be removed.”);
    }
    else if (document.getElementById(childDiv)) {
    var child = document.getElementById(childDiv);
    var parent = document.getElementById(parentDiv);
    parent.removeChild(child);
    }
    else {
    alert(“Child div has already been removed or does not exist.”);
    return false;
    }
    }

    [Reply]

    Dooza reply on October 22nd, 2008 6:30 am:

    The code didn’t paste too well, but I did some more digging and got it working by escaping the single quotes like this:

    onClick=’removeElement(\”dynamicInput\”, \”email” + (counter+1) + “\”);’ />

    [Reply]

    Knix reply on October 23rd, 2008 12:42 am:

    Hi Dooza,

    I’m glad you were able to resolve this on your own. Yea, keeping track of quotes within quotes within quotes can be a really tricky thing!

    [Reply]

    Dooza reply on October 23rd, 2008 4:46 am:

    I am no javascripter, but I know asp/vbscript, so I knew I had to escape them, just wasn’t sure how.

    I have now got both the add and remove scripts working, and added counter– to the remove script so that I could add and remove form fields without hitting the limit. I am very happy with myself, your scripts got me to learn something, so thank you!

  6. MichThom says:

    November 18th, 2008 at 1:09 pm (#)

    Having the same problem Dooza was — trying to have each dynamically added element able to be dynamically removed.

    function addGenre(genreHTML,divName){

    var newdiv = document.createElement(‘div’);
    newdiv.innerHTML = “Genre ” + (Gcounter + 1) + ” : ” + genreHTML + ” “;
    document.getElementById(divName).appendChild(newdiv);
    Gcounter++;

    }

    genreHTML is a php-generated list of ’s.
    genreInput is the parentDiv.

    I’ve tried every combination of single quotes, double quotes, and escaping that I can think of. It returns javascript errors of either invalid arguments or syntax, depending on the quotes used.

    Any help?

    [Reply]

    MichThom reply on November 18th, 2008 1:11 pm:

    Code didn’t transfer right:

    http://pastebin.com/m79f0ba63

    [Reply]

    Knix reply on November 19th, 2008 11:04 pm:

    I have made some edits. It was done manually so please let me know how it works out for you:

    http://pastebin.com/m44815314

    [Reply]

    Knix reply on November 19th, 2008 10:58 pm:

    Hi MichThom,

    This does not seem to be an issue with quotes since the code you have given me looks. I would make sure that all the variables are valid by doing a simple alert on them. Also, you might want to move the “Gcounter++” line to the first line in the function so you do not have to do the “(Gcounter + 1)” in that second line of the function.

    I do not see genreInput anywhere being used in the function so you might want to make sure you have used the correct variable names.

    I hope this helps.

    [Reply]

  7. rocky says:

    November 20th, 2008 at 10:32 am (#)

    Can you provide an example that utilizes both the add and the remove? Messing with your supplied examples, I am unable to get both functioning harmoniously. Meaning, I can add elements, but I can’t remove those newly added elements.

    thank you

    [Reply]

  8. MichThom says:

    November 26th, 2008 at 10:20 am (#)

    I still couldn’t get it to work, but thank you Knix for trying to help me.

    I eventually went on to another solution altogether, that does work harmoniously with both adding and removing elements.

    http://pastebin.com/f76c7c0c2

    Or for a full example, with PHP/mySQL incorporated to prepopulate the form:

    http://pastebin.com/f47d4daf

    Please note that I didn’t do everything in the best way. I query the database using a deprecated method (I think), and see the note at the top of the code for why my method of updating the form isnt the best. But it DOES work, and my point is to show a fully working example of dynamically adding and removing fields, not of proper PHP/mySQL technique.

    [Reply]

  9. MichThom says:

    November 26th, 2008 at 10:23 am (#)

    Here is a fully working example, with PHP and mySQL incorporated to prepopulate the form.

    My PHP/mySQL technique is out of date and isnt the best method, but my point is to show the add/remove.

    http://pastebin.com/f47d4daf

    Or, for simplified code of JUST the javascript and form, without a complete implementation:

    http://pastebin.com/f76c7c0c2

    [Reply]

    Knix reply on November 26th, 2008 11:36 am:

    Hi MichThom,

    Thanks for posting your solution. I hope that it will help many others who come to this site =)

    [Reply]

  10. friar says:

    August 27th, 2009 at 10:21 pm (#)

    body{background-Color:#0f0}
    h1{text-Align:center;text-Decoration:blink}
    table{border-Color:yellow}

    var stack=new Array();
    var olTag=document.createElement(‘ol’);
    function pushStack()//WARAY SEMICOLON…… push
    {
    if(stack.length<=10)
    {
    var item = document.getElementById(“output”).value;
    stack.reverse().push(item);
    //alert(stack.reverse());
    }
    else
    {
    alert(“10 is the Miaximum Entry”)
    return item
    }
    }

    function listshow(thelist)
    {
    var listTag=document.createElement(‘list’);
    for (var i = 0; i < stack.length; i++)
    {
    if(stack.length<=10)
    {
    //stack.splice(1,2);
    var liTag=document.createElement(‘li’);
    txtNode=document.createTextNode(stack[i]);

    }
    }
    olTag.appendChild(liTag);
    liTag.appendChild(txtNode);
    listTag.appendChild(olTag);
    document.childNodes[0].childNodes[1].appendChild(olTag).style.margin = “30 525px”;//append in the HTM document
    }

    function popStack()//pop……..
    {
    var popVal = stack.pop();
    var li = document.getElementsByTagName(‘li’);
    li[0].parentNode.removeChild(li[0-0]);
    if (popVal == undefined)
    return “Nothing left!”;
    else
    return popVal;
    }

    function trial()
    {
    document.getElementById(“output”).value = “”;
    }
    function back()
    {
    document.getElementById(“output”).value = item;
    }
    window.onload=function(){
    document.getElementById(“output”).addEventListener(‘click’,trial,false);
    document.getElementById(“output”).addEventListener(‘blur’,back,false);
    }

    First Come First Serve

    [Reply]

  11. nasim says:

    August 29th, 2009 at 1:01 am (#)

    hello
    these are my add and remove functions,the problem is that remove link only works once and after that it’s kinda disabled and does nothing at all,please help:)here’s my code

    var third_counter = 1;
    function adduniversity(divName){
    var newdiv = document.createElement(‘div’);
    newdiv.innerHTML = “university fieldremove“;
    document.getElementById(divName).appendChild(newdiv);
    third_counter++;
    }

    and my remove function is:

    function removeElement(parentDiv, childDiv){
    var child = document.getElementById(childDiv);
    var parent = document.getElementById(parentDiv);
    parent.removeChild(child);
    third_counter–;
    }

    [Reply]

  12. Nagarajan says:

    September 28th, 2009 at 12:45 am (#)

    hello
    these are my add and remove functions,the problem is that remove link not works please help:)here’s my code

    function setTextInputs(Select) {
    //alert(‘hai’);
    var howmany = Select[Select.selectedIndex].value, add = true;
    alert(howmany);
    var n = 1, Form = Select.form, Div, Input;

    while (Div = document.getElementById(‘Pin’ + n))

    if (n++ > howmany) {
    add = false;
    Form.removeChild(Div);
    }
    if (add)
    for (n; n <= howmany; ++n) {
    Div = document.createElement(‘div’);
    Div.setAttribute(‘id’, ‘Pin’ + n);
    Div.className = ‘inputbox’;
    Div.appendChild(document.createTextNode(‘Pin’ + n + ‘: ‘));
    Form.appendChild(Div);

    Input = document.createElement(‘input’);
    Input.setAttribute(‘type’, ‘text’);
    Input.setAttribute(‘name’, ‘Pin’ + n);
    Div.appendChild(Input);
    document.getElementById(‘one’).appendChild(Div);
    }

    }

    [Reply]

  13. vish says:

    February 25th, 2010 at 11:07 pm (#)

    how can i remove parent div by click remove button which is its child?

    [Reply]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets