user1017882
user1017882

Reputation:

Using jQuery to check if div has text and a span of a certain class

<div class="testDivClass">
    Some text!
    <div>
        <span class="testSpanClass">
        </span>
    </div>
</div>

I want to return true or an object that's not null (basically a boolean to test) - which tells me that this div (of class testDivClass) does contains 'Some text!' and does have a span of class "testSpanClass" (which, please note, is not a direct child of the 'root' div).

Thanks a lot for any suggestions.

So far I have:

$("div.testDivClass:contains('Some text!')");

which is fine, but I don't know where to go from here. Using .children(".testSpanClass") gives me nothing.

EDIT: I've tried .has() - that too returns nothing.

Upvotes: 2

Views: 9504

Answers (2)

Split Your Infinity
Split Your Infinity

Reputation: 4229

I've create a fiddle to demonstrate how to do it...

!!$("div.testDivClass:contains('Some text!')").find(".testSpanClass").length;

The two exclamation marks convert 0 into false and any other number into true.

Upvotes: 1

Esailija
Esailija

Reputation: 140228

$('.testDivClass').is(function() {
    return $(this).text().indexOf("Some text!") > -1 && $(this).find("span.testSpanClass").length
});

Demo: http://jsfiddle.net/Y2KVp/

With selector:

$('.testDivClass').is(':contains("Some text!"):has(span.testSpanClass)');

Selector demo: http://jsfiddle.net/Y2KVp/2/

Upvotes: 5

Related Questions