JavaScript – removing element by part of id


I need remove the <div> element on its id. I know that i can use function such as –

function removeElement(div_id) {
   var div = document.getElementById(div_id);

But the fact is that the id – composite. It consists of a constant part and part that change in every request. This part is a random set of numbers.

I know, i need to use regular expressions in this case. I would be most grateful for an example.


Here is how you can do this with pure JavaScript without any libraries:

var divs = document.getElementsByTagName('div'),
    forEach = Array.prototype.forEach,
    regex = /^foo.*$/;, function (d) {
    if ( !== undefined && regex.test( {

In the example above all div elements which ids start with foo will be removed.
Here is an example:

Answered By – Minko Gechev

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.