KJW
KJW

Reputation: 15251

jQuery: why does :contains selector return undefined?

I am testing a web application and using jQuery to locate a text containing specific string. This is the function I wrote, however, it doesn't seem to respond. I don't know what the tag of the element is ahead of the time.

function get_element_by_text(text) {
    $(document).ready(function (){
        var selector = '*:contains(' + text + ')';
        return $(selector).get(0);
    });
} 

get_element_by_text("Unanswered"); returns undefined

Upvotes: 0

Views: 353

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

The function get_element_by_text is not returning anything, you are having a dom ready handler inside it, the value is returned by that inner function.

So get_element_by_text does not return any value thus you are getting undefined as the result.

Try

function get_element_by_text(text) {
    var selector = '*:contains(' + text + ')';
    return $(selector).get(0);
}
get_element_by_text("Unanswered");

but it will give html as the result because of your selector

Upvotes: 2

Related Questions