0

Suppose I have div's and p's in HTML and they both contain same text. I want to highlight the searched text from html paragraph only. How can I do that using jQuery ?

Like

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

I want to highlight the 'world' in the paragraph tag.

4
  • but there is also hello in <p> tag, don't u want to highlight that one?? Commented May 13, 2011 at 6:17
  • var nodes = document.getElementsByTagName("p"); for (var index=0; index<nodes.length; index++) { var node = nodes[index]; if (node.innerHTML.indexOf(searchTerm) != -1) { node.style.backgroundColor = "green"; } } Commented May 13, 2011 at 6:19
  • 1
    @aroth: 1) Why would you post code in a comment? 2) Why use framework-less js when it's tagged as jQuery? Commented May 13, 2011 at 6:23
  • @Demian Brecht - #2 is the answer to #1; the OP asked for an answer using jQuery, and I was providing non-jQuery code, so it's not really appropriate as an answer. As for #2, I think jQuery is overused for solving simple problems like this one, and wanted to point out that a trivial non-framework solution exists. Commented May 13, 2011 at 6:32

5 Answers 5

4

You can add a class to the entire p element.

$('p:contains("Hello")').addClass('highlight');

Otherwise, you'll need to iterate over the text nodes and then wrap the match with a span.

Sign up to request clarification or add additional context in comments.

1 Comment

Ugh.. Damn AFK'ing in the midst of fiddling : / (6 minutes later..) +1 for being more focused than I ;)
1

Use the :contains selector.

var str = "World";

$('p:contains('+str+')').css('background-color', 'yellow');

Fiddle here

Comments

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
    }
});

Comments

0

This will do case insensitive search and add a highlight class.

var str = /world/gi;
jQuery("p").each(function() {
    if(jQuery(this).text().match(str) {
        jQuery(this).addClass("highlight");
    }
});

Comments

-1

Use this inside the body

<script>

    $("body").find("p").eq(1).css("background-color","green");
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.