Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: check if string exist in element, return boolean

Tags:

jquery

Assuming I have this:

<div id="elementId">bla bla bla some text bla bla</div>

I want to check if this div text contains 'some text', then return true, otherwise return false, how to do that?

like image 241
evilReiko Avatar asked Dec 29 '10 10:12

evilReiko


People also ask

How check string exist or not in jQuery?

How to find if a word or a substring is present in the given string. 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.

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.

What does jQuery find return?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

How check textbox ID exist or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.


2 Answers

var isContains = $('#elementId').text().indexOf('some text') > -1; 
like image 71
Darin Dimitrov Avatar answered Oct 04 '22 10:10

Darin Dimitrov


You can use the :contains() selector and check the .length to see if it matched anything, like this:

return $("#elementId:contains('some text')").length > 0; 
like image 23
Nick Craver Avatar answered Oct 04 '22 09:10

Nick Craver