Kamran Ahmed Kamran Ahmed - 5 months ago 35
HTML Question

Remove all the DOM elements with a specific tag name in Javascript

How can I remove all the elements with a specific tag name using Javascript. For example, I did the following:

var els = document.getElementsByTagName("center");


and it returned an array of all the
center
elements. How may I remove all these elements?

Coming from Remove all child elements of a DOM node in JavaScript? and Javascript DOM remove element I know that I can loop through
els
, find the parent of each element and then remove that specific node. But is there anyother way provided by javascript. Like we can do
$('center').remove()
in jquery and it removes all the elements with
center
tag. Anything similar to that in Javascript?

Answer

"it returned an array of all the center elements."

Well, it returned an array-like object (a live NodeList or an HTMLCollection depending on the browser).

"How may I remove all these elements?"

You have to loop through the list removing them one at a time as you mentioned later in your question. If you find yourself doing that a lot, encapsulate the looping inside a function so that you don't have to repeat it.

"we can do $('center').remove() in jquery and it removes all the elements with center tag. Anything similar to that in Javascript?"

jQuery is a collection of JavaScript functions, so it can't do anything JavaScript can't do. jQuery's .remove() method (like most other jQuery methods) will loop internally, it just saves you having to think about it. So that comes back to what I already mentioned above, encapsulate the loop/remove code in a function so that you can use it from any part of your code.