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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With