30

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?

3
  • Do you mean if it contains the string "some text" or just some text ? Commented Dec 29, 2010 at 10:16
  • @Aerus There are quotes around the words "some text" in the question. Commented Dec 29, 2010 at 10:16
  • 1
    @Jacob ok, i was confused since your answer checks for "bla" instead of "some text" Commented Dec 29, 2010 at 10:18

5 Answers 5

42
var isContains = $('#elementId').text().indexOf('some text') > -1;
Sign up to request clarification or add additional context in comments.

Comments

8

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;

4 Comments

@Nick Why use this when you can use native JS methods?
@Jacob - I don't follow, since when are $() and .text() native JS methods? :contains() calls the same thing underneath.
@Jacob - just something to keep in mind, .innerText won't work in Firefox :) quirksmode.org/dom/w3c_html.html#t04
@Nick Thanks for that. I never really use .innerText anyway, so yeah jQuery helps there for sure. As much as I love jQuery, sometimes I feel that it overlaps onto features that should be left alone. This kind of overlapping is what IMO contributes to people thinking that jQuery is a language, when really it's just a framework.
3

I used the same way of the buddy above...:

if($('#div_searched').text().indexOf('bla') != -1)

This will return true when it found the word bla on div_searched

Comments

1
let myNode = document.getElementById("elementId")
const Value = myNode.textContent || myNode.innerText
const txtExist = Boolean(Value.replace(/\s/g, ""));

Note: innerText does work in IE, also textContent is not supported in IE8 and older

Comments

0

I think this should also work.

return $("#elementId:contains('some text')").length ? true : false;

It should return true if length greater than 0, otherwise it will return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.