假设我在HTML中有div和p,它们都包含相同的文本。我想突出显示来自html段落的搜索文本。我怎么能用jQuery做到这一点?
像
<div>Hello</div>
<div>World</div>
<p>Hello</p>
<p>World</p>
我想在段落标签中突出显示“世界”。
答案 0 :(得分:4)
您可以向整个p
元素添加一个类。
$('p:contains("Hello")').addClass('highlight');
否则,您需要iterate over the text nodes and then wrap the match with a span
。
答案 1 :(得分:1)
使用:contains
选择器。
var str = "World";
$('p:contains('+str+')').css('background-color', 'yellow');
<强> Fiddle here 强>
答案 2 :(得分:0)
$('p').each(function(index) { // Find every paragraph and run through them
if($(this).text() === "world") { // Check if current paragraph's text is "world"
$(this).addClass("itemFound"); // Apply styling
}
});
答案 3 :(得分:0)
这将执行不区分大小写的搜索并添加突出显示类。
var str = /world/gi;
jQuery("p").each(function() {
if(jQuery(this).text().match(str) {
jQuery(this).addClass("highlight");
}
});
答案 4 :(得分:-1)
在体内使用
<script>
$("body").find("p").eq(1).css("background-color","green");
</script>