Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery .filter() to select specific text within div

HTML:

<p class="greeting">
  hello, my name is kevin. what's yours?
</p>

jQuery:

$("p.greeting").filter(function (){
  return $this.text() === "my name is";
}).css("background", "green");

I'm trying to isolate the words "my name is" in the <p class="greeting"> tag. Can anyone help me with the jQuery as it doesn't seem to work. Thanks.

like image 878
pruett Avatar asked Oct 31 '11 20:10

pruett


People also ask

How do I search for a specific word in a string in jQuery?

We can use the replace() method with either regular expression or string as an argument. How to find the number of occurrences of a particular word or a string in a given string or paragraph. In this case, we will use the indexOf() Method in JavaScript to find the number of occurrences of desired word or substring.

How do I check if a div contains a text?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How do I select a span containing a specific text value using jQuery?

To select a span containing a specific text value using jQuery, we can select all the spans and then use the filter method to find the one with the given text value. We call $(“span”) to get all the spans. Then we spread the spans into an array with the spread operator.

How do we filter out elements using jQuery?

The filter() method returns elements that match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned. This method is often used to narrow down the search for an element in a group of selected elements.


1 Answers

Here you go:

CSS:

.highlight { background-color: yellow; }

JavaScript:

var text = 'My namE iS';

$( 'p.greeting' ).html( function ( i, html ) {
    var regexp, replacement;

    regexp = RegExp( '(' + text + ')', 'gi' );
    replacement = '<span class="highlight">$1</span>';

    return html.replace( regexp, replacement );
});

Live demo: http://jsfiddle.net/SGCDS/5/

like image 109
Šime Vidas Avatar answered Oct 20 '22 12:10

Šime Vidas