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.
In this case, we will use the includes() method which determines whether a string contains the specified word or a substring. If the word or substring is present in the given string, the includes() method returns true; otherwise, it returns false. The includes() method is case sensitive.
jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
Your code contains two problems:
==
, not =
.jQuery.text()
joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some'
and the second contains 'Text'
, then your code will incorrectly think that there exists an element that contains 'someText'
.I suggest the following instead:
if ($('#field > div.field-item:contains("someText")').length > 0) {
$("#somediv").addClass("thisClass");
}
Yes, I now made think for me. And it works fine!!!
if($("div:contains('CONGRATULATIONS')").length)
{
$('#SignupForm').hide(500);
}
if( $("#field > div.field-item").text().indexOf('someText') >= 0)
Some browsers will include whitespace, others won't. >=
is appropriate here. Otherwise equality is double equals ==
Ayman is right but, you can use it like that as well :
if( $("#field > div.field-item").text().indexOf('someText') >= 0) {
$("#somediv").addClass("thisClass");
}
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