$('.test').css('background','red');
<div id="example">Some text</div>
How can I .addClass('test')
if #example
contains the word "text"?
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
The contains() method returns true if a node is a descendant of a node. The contains() method returns false if not.
just use :contains
pseudoclass
$('#example:contains("text")').addClass('test');
this will add the class to #example
if it contains 'text'
You can use $("#example")
to get a jQuery wrapper for the element, then use text()
to get its text, and use String#indexOf
, e.g.:
var ex = $("#example");
if (ex.text().indexOf("text") !== -1) {
ex.addClass("test");
}
You can also use :contains("text")
in the selector as F. Calderan shows, although note that when you use non-standard pseudo-selectors like that, jQuery can't use the underlying browser's built-in stuff for finding elements, so it can be slower. The above will allow jQuery to use document.getElementById
. There are only a few situations where the speed really matters, though.
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