We have seen how jQuery can be used to remove elements from DOM.Now let us see how we can Dynamically remove content from DOM using JavaScript.

Like always let us start with HTML

Nothing fancy here, we have a simple HTML page with four text-boxes(magic-text-box) inside a div (div-textbox-here) and a button(btn-remove-textbox) to remove those text-boxes.

That’s all the HTML we need for now. Let’s call our button and ask it to listen for a click.

So here we first call(‘getElementById’) our button(btn-remove-textbox) and ask it to listen(‘addEventListener’) for a ‘click’ event. Next we will tell the button what it has to do once it hears a ‘click’.

Once our button(btn-remove-textbox) hears a click we ask it to get the div(div-textbox-here) that contains all the text-boxes. Once we have the div we get all the text-boxes inside it using class name (‘getElementsByClassName’). Remember we have given the same class name(magic-text-box) to each of our text-boxes.

getElementsByClassName’ will return an ‘array’ of all the text-boxes with matching class name. Once we have the array, we remove the first element of the array, since we want to remove (‘removeChild’) the first text-box. Remember in an array ‘0’ is the first element.

And that’s about it. Of-course we can do a lot more. Like making sure that there is at-least one text-box remains in the div(user cannot remove all the text-boxes).

Same code as before but here we have added an ‘if condition’. This ‘if condition’ will check if the number(‘length’) of text-boxes is more then one only then remove the first text-box from the array.

And that’s how you Dynamically remove content from DOM using JavaScript.

Get full code on github.

SiteLock