2

I want to ask what is the best way to search string and get matched element?

//I want to get similar or matched element and the index of it.
//Search key ward 
var key = 'Pap'; 
<ul>
 <li>Papa</li>
 <li>Mama</li>
</ul>

My Idea now is use $.each and match its text of each, but I believe that should be a wrong way. However, I couldn't find any references from net about this question.

Thank you very much.

1 Answer 1

6

Use :contains selector

$('*:contains("'+key+'"):last')

To find exact match will the whole text in element use this

$.fn.exactMatch = function (key) {
    var p = $(this).find(':contains("' + key + '"):last');
    if (p.text() == key) {
        p.css('background', 'yellow');
    } else {
        //Not exact match function if wanted
    }
}

To use this function do this

$(el).exactMatch(key);
Sign up to request clarification or add additional context in comments.

12 Comments

The :last seems redundant, unless I'm missing something?
When you use contains you get all the parents of the element you want to select, so i use last to get the exact element that contains "key"
I tired $(el.selector + ':contains("'+ key +'"):last') and $(el).find('*:contains("'+ key +'"):last'), both didnt work, What am I missing?
the el here means the ul element
If you mean var key = "Hello world" then yes, but the key has to be exactly matched to the elements string
|

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.