6

I have a function to get the <li> tag at the top that contains the key specified to it, anywhere in the text.

But I want to have the <li> that starts with the key specified to it. Here is the code:

function displaySearchResult(key){
   var li=$('.listcontainer ul li:contains('+key+')');
   li.parent().prepend(li);
}

So how to get the <li> tag whose text starts with the specified key?

remio
  • 1,210
  • 2
  • 14
  • 36
Chetana Kestikar
  • 600
  • 6
  • 23

2 Answers2

13

Use filter.

var li = $('.listcontainer ul li').filter(function() { return $(this).text().indexOf(key) === 0; });
Dogbert
  • 188,810
  • 39
  • 339
  • 353
  • Thanks for the solution. But its not working. The function i have mentioned is called on keyup event. So will it work on the key having more than a character? – Chetana Kestikar Dec 17 '12 at 12:33
  • @ChetanaKestikar, yes, it should work. If it doesn't, we'll need to see more code. – Dogbert Dec 17 '12 at 12:44
0

Please check filter() in jquery.

Filter

Filter demo as specified in api.jquery

 $('li').filter(function(index) {
   return $('strong', this).length == 1;
 }).css('background-color', 'red');​
RGR
  • 1,431
  • 2
  • 22
  • 33