Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/421.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环遍历容器并移除没有特定类的div_Javascript_Jquery_Html - Fatal编程技术网

Javascript 循环遍历容器并移除没有特定类的div

Javascript 循环遍历容器并移除没有特定类的div,javascript,jquery,html,Javascript,Jquery,Html,我知道这有一个简单的解决方案。也许是因为时间晚了,但我遇到了麻烦。我有一个容器div#jewelscocontainer,里面有一列子div。我在这样的物体中抓住它: var existingBoardItems = $('#jewelsContainer').html(); [].forEach.call(document.querySelectorAll('#container :not(.a)'), function(e,i){ e.parentNode.removeChild(

我知道这有一个简单的解决方案。也许是因为时间晚了,但我遇到了麻烦。我有一个容器
div#jewelscocontainer
,里面有一列子div。我在这样的物体中抓住它:

var existingBoardItems = $('#jewelsContainer').html();
[].forEach.call(document.querySelectorAll('#container :not(.a)'), function(e,i){
    e.parentNode.removeChild(e);
})
此对象生成
#jewelscocontainer
容器div中所有div的列表

i、 e.以前

<div class="jewel jewel_5" data-row="1" data-col="0" data-jewel="5" style="left: 0px; top: 40px;"></div>
<div class="jewel jewel_3" data-row="0" data-col="3" data-jewel="3" style="top: 0px; left: 120px;"></div>
<div class="jewel jewel_5" data-row="0" data-col="4" data-jewel="5" style="top: 0px; left: 160px;"></div>
<div class="jewel jewel_4" data-row="0" data-col="5" data-jewel="4" style="top: 0px; left: 200px;"></div>
<div class="aff_score" style="left:0px; top:0px;">+10</div>
...
尝试在这个上下文中使用选择器,不需要迭代所有div

$('#jewelsContainer div:not(.jewel)').remove();
试试这个方法

$('#jewelsContainer').find('div').each(function () {
   if (!$(this).hasClass('jewel')) {
        $(this).remove()
    }
});
localStorage.setItem('existingBoardItems',$('#jewelsContainer').html());
console.log(localStorage.getItem('existingBoardItems'));

虽然答案已经被接受,但我觉得非jQuery解决方案也应该出现
:not
不是jQuery选择器,它是一个CSS选择器,在jQuery和本机
querySelector
querySelectorAll
中都受支持

移除上述元素可能是这样的:

var existingBoardItems = $('#jewelsContainer').html();
[].forEach.call(document.querySelectorAll('#container :not(.a)'), function(e,i){
    e.parentNode.removeChild(e);
})
或者这个:

var elms = document.querySelectorAll('#container :not(.a)');
for (var i = 0; i < elms.length; i++) {
    elms[i].parentNode.removeChild(elms[i]);
}
var elms=document.querySelectorAll(“#容器:非(.a)”;
对于(变量i=0;i


这是一个例子,它表明香草在这种情况下的速度是它的两倍多。编辑:似乎在chrome上速度更快。

这不会删除此元素<代码>为什么您可以解释sridhar代码的错误。我想是的works@SridharR现在看。OP想要删除没有类
jewel
的元素。。但是这个代码会考虑<代码>宝石> 4/代码>与<代码>宝石> <代码> @ RajabrabuavaLavasasy谢谢您的解释<代码>:/代码>谢谢,我知道这是一个简单的解决方案。“我必须睡一会儿。”杰森很高兴能帮上忙。。!