I have something like this
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>
How can I remove divs where "data-count" attribute value is less than 15?
This is more efficient because it only selects div
s with the data-count
attribute and only constructs a jQuery object once for each element:
$('div[data-count]').each(function () {
var $this = $(this);
if ($this.attr('data-count') < 15) {
$this.remove();
}
});
Demo:
$('button').on('click', function () {
$('div[data-count]').each(function () {
var $this = $(this);
if ($this.attr('data-count') < 15) {
$this.remove();
}
});
});
div[data-count]:before {
content: "<div data-count=\"" attr(data-count) "\">";
}
div[data-count]:after {
content: "</div>";
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>
An alternative solution in native JavaScript:
var divs = document.querySelectorAll('div[data-count]'),
div, i;
for (i = 0; i < divs.length; i++) {
div = divs[i];
if (div.getAttribute('data-count') < 15) {
// this will not affect iteration because querySelectorAll is a non-live NodeList
div.parentNode.removeChild(div);
}
}
Demo:
var button = document.querySelector('button');
button.addEventListener('click', function () {
var divs = document.querySelectorAll('div[data-count]'),
div, i;
for (i = 0; i < divs.length; i++) {
div = divs[i];
if (div.getAttribute('data-count') < 15) {
// this will not affect iteration because querySelectorAll is a non-live NodeList
div.parentNode.removeChild(div);
}
}
});
div[data-count]:before {
content: "<div data-count=\"" attr(data-count) "\">";
}
div[data-count]:after {
content: "</div>";
}
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>
Please try this:
$('div').each(function() {
if ( $(this).attr('data-count') < 15 ) {
$(this).remove();
}
});
DEMO
This may not be the most efficient way to do it but it works:
function removeLowData() {
for(var i = 1; i < 15; i++) {
var elements = $("[data-count='" + i + "']");
for(var j = 0; j < elements.length; j++) {
$(elements[j]).remove();
//or use .hide() if you still want them to be part of the dom but not visible
}
}
}
Just call removeLowData()
whenever you need to remove the divs
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