Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all element without attribute

I try to understand how to remove all children elements without specified attribute for example:

This is the html:

<div class="container">
  <span></span>
  <div></div>
  <strong data-*></strong>
  <p></p>
  <div data-*></div>
</div>

What i want is to remove all element inside the container and without data-* attribute.

data-*

The attribute can be data-anything (data-color, data-border, etc).

I'm looking javascript only solution.

like image 449
Aviel Fedida Avatar asked Feb 20 '26 14:02

Aviel Fedida


1 Answers

Using .filter(), .some() and .forEach() should do the trick.

var els = document.querySelectorAll(".container *");

[].filter.call(els, function(el) {
    return ![].some.call(el.attributes, function(attr) {
        return /^data/i.test(attr.name);
    });
}).forEach(function(el) {
    el.parentNode.removeChild(el);
});

You'll need patches for old browsers, but you probably knew that already.


If like me, you like reusable functions:

var els = document.querySelectorAll(".container *");

[].filter.call(els, els_with_no_data)
  .forEach(remove_nodes);

function remove_nodes(el) {
    el.parentNode.removeChild(el);
}

function has_data_attrs(attr) {
    return /^data/i.test(attr.name);
}

function els_with_no_data(el) {
    return ![].some.call(el.attributes, has_data_attrs)
}

And then using Array generics (in supported browsers, otherwise polyfiilled):

var els = document.querySelectorAll(".container *");

Array.filter(els, els_with_no_data)
     .forEach(remove_nodes);

function remove_nodes(el) {
    el.parentNode.removeChild(el);
}

function has_data_attrs(attr) {
    return /^data/i.test(attr.name);
}

function els_with_no_data(el) {
    return !Array.some(el.attributes, has_data_attrs)
}
like image 68
cookie monster Avatar answered Feb 22 '26 04:02

cookie monster