Hi is there anyway to search text in dom, as we do for SQL query LIKE?
i mean, i have.
<ul>
<li>ab</li>
<li>abrecot</li>
<li>abus</li>
<li>aby</li>
<li>abrea</li>
</ul>
i would like to search for "abre" and so return in text ASC order:
<li>abrea</li>
<li>abrecot</li>
is this possible?
definitely the query would looks like doing:
SELECT <li> FROM <ul> WHERE text LIKE 'abre%' ORDER BY text ASC; :))
Hi is there anyway to search text in dom, as we do for SQL query LIKE?
i mean, i have.
<ul>
<li>ab</li>
<li>abrecot</li>
<li>abus</li>
<li>aby</li>
<li>abrea</li>
</ul>
i would like to search for "abre" and so return in text ASC order:
<li>abrea</li>
<li>abrecot</li>
is this possible?
definitely the query would looks like doing:
SELECT <li> FROM <ul> WHERE text LIKE 'abre%' ORDER BY text ASC; :))
Share
Improve this question
asked Sep 27, 2011 at 13:17
Filippo orettiFilippo oretti
49.8k96 gold badges229 silver badges351 bronze badges
2
- 1 It's not a duplicate, but this may give you some ideas: stackoverflow./questions/5324798/… – Kiley Naro Commented Sep 27, 2011 at 13:19
- uhm it search in array wich will be an array of elements, but he search for %text% i would like to search for text% :P – Filippo oretti Commented Sep 27, 2011 at 13:21
3 Answers
Reset to default 6As you are looking for elements whose text starts with a specified string, you can use the filter
method:
var x = $("ul li").filter(function() {
return $(this).text().substr(0, 4) === "abre";
});
This will only return elements which have the string "abre" at the start. The other answers using the contains
method will return elements with the string found anywhere within them, which does not match your pseudo-SQL query.
Here's a working example of the above.
I think you would want the jQuery 'contains' function, have a look at the docs here:
http://api.jquery./contains-selector/
Your example would probably look like this:
$("li:contains('abre')")
EDIT to include the ments here, if you are looking for "starts with", you can do this on an element using the following syntax:
$('li[anAttribute^="abre"]')
But this assumes you have an attribute to query which i don't think you do, in which case the filters answer will likely suit your needs best.
The :contains()
selector is probably what you're looking for:
http://api.jquery./contains-selector/
QUOTE:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery./jquery-latest.js"></script>
</head>
<body>
<div>John Resig</div>
<div>George Martin</div>
<div>Mal John Sinclair</div>
<div>J. Ohn</div>
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
</body>
</html>