Delete specific divs by attribute conditions
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 to remove a div where the value of the "data-count" attribute is less than 15?
+5
3 answers
This is more efficient since it selects a div using the data-count attribute and only creates a jQuery object for each element only once:
$('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> 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> +4
This may not be the most efficient way to do this, 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() when you need to remove divs
+2