我想获取包含特定单词的所有字符串, 例如:
<div>
<div>
<span>
<h3>In Paris (Mark Bartels) worked for about 50 years.</h3>
</span>
</div>
<div>
<span>
<h3>In America (Henry Bartels) worked for about 50 years.</h3>
</span>
</div>
<div>
<span>
<h3>In Europe (Mark Bartels) worked for about 50 years.</h3>
</span>
</div>
</div>
在上面的字符串中,我必须检查“Mark”,现在我想显示包含“Mark”一词的所有字符串。
我已经尝试过以下方式,但它对我没有帮助。
var elem = $('body').find(':contains(Mark)').not('script, style, link');
var a = elem.parent();
var tag = a;
console.log(tag);
$("#sentence").append(elem.text());
$("#sentence").append('<br />');
答案 0 :(得分:6)
迭代包含字符串的所有元素并附加innerText。
:not(:has(*))
:选择所有没有子元素的元素(不包括文本节点)Reference :contains(Mark)')
:选择包含文本Mark
:not(script)
:排除<script>
元素
// Get all the h3 elements which contains `Mark` in the innerText
// Iterate over them
$('body').find(':not(:has(*)):contains(Mark):not(script)').each(function() {
// Append to the element
console.log($(this)[0]);
$('#sentence').append($(this).text() + '<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<span>
<h3>In Paris (Mark Bartels) worked for about 50 years.</h3>
</span>
</div>
<div>
<span>
<h3>In America (Henry Bartels) worked for about 50 years.</h3>
</span>
</div>
<div>
<span>
<h3>In Europe (Mark Bartels) worked for about 50 years.</h3>
</span>
</div>
</div>
<div id="sentence"></div>
答案 1 :(得分:0)
让我们假设h3
有一个共同的班级text
,然后我们可以使用indexof
轻松找出Mark
出现的地方
$('.text').each(function () {
if ($(this).text().indexOf('Mark') >= 0) {
$("#sentence").append($(this).text() + '<br />');
}
});