JavaScript – removing element by part of id

Issue

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);
   element.parentNode.removeChild(div);
}

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.

Solution

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

var divs = document.getElementsByTagName('div'),
    forEach = Array.prototype.forEach,
    regex = /^foo.*$/;

forEach.call(divs, function (d) {
    if (d.id !== undefined && regex.test(d.id)) {
        d.parentNode.removeChild(d);
    }
});‚Äč

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

Answered By – Minko Gechev

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.