按属性条件删除某些div

时间:2015-07-08 03:59:26

标签: html greasemonkey

我有类似的东西

<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>

如何删除其中&#34;数据计数&#34;属性值小于15?

3 个答案:

答案 0 :(得分:4)

请尝试:

$('div').each(function() {
    if ( $(this).attr('data-count') < 15 ) {
        $(this).remove();
    }
});

DEMO

答案 1 :(得分:4)

这更有效,因为它只选择div属性为data-count,并且只为每个元素构造一次jQuery对象:

$('div[data-count]').each(function () {
    var $this = $(this);

    if ($this.attr('data-count') < 15) {
        $this.remove();
    }
});

演示:

&#13;
&#13;
$('button').on('click', function () {
    $('div[data-count]').each(function () {
        var $this = $(this);

        if ($this.attr('data-count') < 15) {
            $this.remove();
        }
    });
});
&#13;
div[data-count]:before {
    content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
    content: "</div>";
}
&#13;
<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>
&#13;
&#13;
&#13;

原生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);
    }
}

演示:

&#13;
&#13;
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);
        }
    }
});
&#13;
div[data-count]:before {
    content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
    content: "</div>";
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

这可能不是最有效的方法,但它有效:

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
        }
    }
}

只要您需要移除div

,只需致电removeLowData()即可