我试图通过其中包含的字符串选择某些对象。
例如,如果我定义了一个单词数组,可以这样说:
var searchTerms = ["apple", "banana"];
如何从包含其中一个术语的一系列相同对象中进行选择并从DOM中删除包含对象? 举个例子:
<section class="node_category">
<h3>orange</h3>
</section>
<section class="node_category">
<h3>apple</h3>
</section>
感谢您的帮助!
*为清晰起见而编辑
答案 0 :(得分:1)
使用contains
例如
if ( $(".node_category h3:contains('orange')").size() > 0 )
{
//if there is any node_category which has h3 that contains orange
}
<强>样本强>
var searchTerms = ["apple", "banana"];
searchTerms.forEach( function(value){
$(".node_category h3:contains('" + value + "')").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="node_category">
<h3>orange</h3>
</section>
<section class="node_category">
<h3>apple</h3>
</section>
如果您希望删除父元素(section class="node_category">
)以匹配h3
,请尝试
var searchTerms = ["apple", "banana"];
searchTerms.forEach( function(value){
$(".node_category h3:contains('" + value + "')").parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="node_category">
<h3>orange</h3>
</section>
<section class="node_category">
<h3>apple</h3>
</section>
答案 1 :(得分:1)
如果您需要灵活的解决方案,也可以使用quicksearch:https://github.com/riklomas/quicksearch
一个小例子:
var qs=$('input#search').quicksearch('table tbody td');
$("#append").on("click", function(e) {
$("tr").append('<td>'+$("#search").val()+'</td>');
qs.cache();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.quicksearch/2.2.0/jquery.quicksearch.min.js"></script>
/* Example form */
<form>
<input type="text" id="search">
<input type="button" id="append" value="ajax">
</form>
/* Example table */
<table>
<tbody>
<tr>
<td>Test cell</td>
<td>Another test cell</td>
</tr>
</tbody>
</table>
答案 2 :(得分:1)
没有jQuery
var searchTerms = ["apple", "banana"],
nodes = [].slice.call(document.querySelectorAll('h3')); // get all h3's and convert from nodelist to array
// loop through h3's
nodes.forEach(function(node) {
if (searchTerms.indexOf(node.textContent) !== -1) {
//only remove h3
node.parentNode.removeChild(node);
// remove section as well
// node.parentNode.parentNode.removeChild(node.parentNode);
}
});