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.
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With