如何使用jQuery在HTML中突出显示<p> not </p> <div>?</div>

时间:2011-05-13 06:09:17

标签: jquery html

假设我在HTML中有div和p,它们都包含相同的文本。我想突出显示来自html段落的搜索文本。我怎么能用jQuery做到这一点?

<div>Hello</div>
<div>World</div>
<p>Hello</p>
<p>World</p>

我想在段落标签中突出显示“世界”。

5 个答案:

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