How to dynamically remove/delete elements via JavaScript


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. <div id="parent" style="border: 1px solid red; padding: 10px;">
  2.      I am the parent div.
  3.      <div id="child" style="border: 1px solid green; padding: 10px;">
  4.            I am a child div within the parent div.
  5.      </div>
  6. </div>
  7. <p>&nbsp;</p>
  8. <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. function removeElement(parentDiv, childDiv){
  2.      if (childDiv == parentDiv) {
  3.           alert("The parent div cannot be removed.");
  4.      }
  5.      else if (document.getElementById(childDiv)) {     
  6.           var child = document.getElementById(childDiv);
  7.           var parent = document.getElementById(parentDiv);
  8.           parent.removeChild(child);
  9.      }
  10.      else {
  11.           alert("Child div has already been removed or does not exist.");
  12.           return false;
  13.      }
  14. }

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. <div id="parentDiv" style="border: 1px solid red; padding: 10px;">
  2.      My name is <b>parentDiv</b>.  I cannot be removed.
  3.      <div id="child1" style="border: 1px solid green; padding: 10px; margin: 10px;">
  4.           My name is <b>child1</b>.
  5.      </div>
  6.      <div id="child2" style="border: 1px solid blue; padding: 10px; margin: 10px;">
  7.           My name is <b>child2</b>.
  8.      </div>
  9.      <div id="child3" style="border: 1px solid purple; padding: 10px; margin: 10px;">
  10.           My name is <b>child3</b>.
  11.      </div>
  12. </div>
  13. <p>&nbsp;</p>
  14. 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);">
  15. <br><br>
  16. For those who are lazy in typing in the actual names, we have these handy-dandy buttons:
  17. <input type="button" value="Remove child1" onClick="removeElement('parentDiv', 'child1');">
  18. <input type="button" value="Remove child2" onClick="removeElement('parentDiv', 'child2');">
  19. <input type="button" value="Remove child3" onClick="removeElement('parentDiv', 'child3');">
  20. <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. <div id="parentDivElement" style="border: 1px solid red; padding: 10px;">
  2.      My name is <b>parentDivElement</b>.  I cannot be removed.
  3.      <div id="childOne" style="border: 1px solid green; padding: 10px; margin: 10px;">
  4.           My name is <b>childOne</b>.
  5.      </div>
  6.      <div id="childTwo" style="border: 1px solid blue; padding: 10px; margin: 10px;">
  7.           My name is <b>childTwo</b>.
  8.      </div>
  9.      <div id="childThree" style="border: 1px solid purple; padding: 10px; margin: 10px;">
  10.           My name is <b>childThree</b>.
  11.      </div>
  12. </div>
  13. <p>&nbsp;</p>
  14. <input id="cb1" type="checkbox" value="childOne" onClick="removeElement('parentDivElement', this.value);"><label for="cb1">Remove <b>childOne</b></label>
  15. <input id="cb2" type="checkbox" value="childTwo" onClick="removeElement('parentDivElement', this.value);"><label for="cb2">Remove <b>childTwo</b></label>
  16. <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.

If you are interested in hiding content via JavaScript and not necessarily deleting or removing them from the DOM, see my post on How to Hide and Show Your Div.

Update: Since my initial writing of this blog post, some great JavaScript libraries have been implemented which makes removing elements much easier! One of these JavaScript libraries is jQuery and I have done a similar post on removing elements from the DOM: How to dynamically remove elements from the DOM via jQuery.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!





Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

30 thoughts on “How to dynamically remove/delete elements via JavaScript”

  1. Thank you Knix for these scripts. After trying to do the same thing with innerHTML, and spending a couple of hours trying to get this to work, your solution worked perfectly in both browsers, and saved me a huge amount of time. Your examples and explanations also made the solutions clear. Thanks again.

    1. Hey Vish,

      The way it works is ONLY the parent of an element can call the removeChild function (atleast in actionscript), so to do as you want all you need to do is to create a parent div.. of the parent div’s you want removing

      eg. the examples above are

      parent
      child1
      child2

      so now you access “parent” and tell it to remove its child div child1 or 2. if you want to go one further you just need to make a new upper level – you could even use the element if you like but i wont for this

      topmost div
      parent div 1
      child div 1 1
      child div 1 2
      child div 1 3

      parent div 2
      child div 2 1
      child div 2 2
      child div 2 3

      parent div 3
      child div 3 1
      child div 3 2
      child div 3 3

      with that structure you can now use the “masterDiv” as the parent of each “parent” div to remove it from the page.

      hope that helps, good luck javascript-ing!

      Bim

  2. 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);
    }

    }

  3. 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–;
    }

  4. 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

  5. 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.

  6. 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

  7. 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?

    1. 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.

  8. 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;
    }
    }

    1. 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) + “\”);’ />

      1. 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!

        1. 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!

  9. 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?

    1. Hi shammim,

      Here is an example of your request:

      Parent of Block

      Block

      A DIV element within Block

       

      HTML code:

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

      I hope this helps.

  10. 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.

    1. 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.

      1. 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.

  11. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *