Muhammad Umer
Muhammad Umer

Reputation: 18097

Find element in which regex matches using jquery?

Is there a way to find element using regex to search in its text. So for example, if element p has word kobra in it then jquery selector returns the list of those elements optionally wrapping matched words in span element.

I need it to create search functionality. Basically there is a li based list. User enters a term, then all elements are gotten using that regex to element selector, then upon clicking next user is scrolled to that position.

Upvotes: 0

Views: 318

Answers (2)

Mouser
Mouser

Reputation: 13304

If nothing fancy is needed, based upon your question, user enters a search term, search term is displayed: use jQuery's contains selector, no regex is needed:

http://api.jquery.com/contains-selector/

 $('element:contains(kobra)') 

Upvotes: 3

Hayden Schiff
Hayden Schiff

Reputation: 3330

Use a jQuery selector that matches all the elements you want to search in, then run your regex query on each of them. Here's some rough pseudocode:

$('.myParagraphs').each(function() {
  var obj = $(this);
  if (obj.text().matches(myRegexp)) {
    //code to scroll to that element
  }
});

Upvotes: 1

Related Questions