Gavin Sellers
Gavin Sellers

Reputation: 664

Search an element to see if it contains a certain string

What's the easiest way to search a div for a text string using jquery? I specifically want to search a div with an id and see if it contains $(this).text(). The purpose of this is to be able to append elements to a div but be able to prevent the same string from being written to the same div over and over.

Upvotes: 1

Views: 127

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075427

I specifically want to search a div with an id and see if it contains $(this).text().

I think I'd probably go with String#indexOf:

var div = $("#theId"),
    text = $(this).text();
if (div.text().indexOf(text) === -1) {
    // It doesn't have it, add it
    div.append(text); // Or whatever
}

Upvotes: 2

VisioN
VisioN

Reputation: 145458

You can use either :contains selector or filter method (if you need precise coincidence):

$("div[id]").filter(function() {
    return $(this).text() == str;
});

Upvotes: 0

Related Questions