简体   繁体   中英

jQuery search text in elements as SQL query LIKE?

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; :))

As 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.com/contains-selector/

Your example would probably look like this:

$("li:contains('abre')")

EDIT to include the comments 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.com/contains-selector/

QUOTE:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<div>John Resig</div>

<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>


<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM