jquery filter: get the first match only?
Asked Answered
A

4

8

I want to find a match in the link's url and then do something about that link, such as changing it colour, etc.

$("a").filter("[href*='id=10']").css({color: 'red'});

html,

<a href="http://website.come/folder/file.php?id=9&ajax=true">0</a>
<a href="http://website.come/folder/file.php?id=10&ajax=true">1</a>
<a href="http://website.come/folder/file.php?id=20&ajax=true">2</a>
<a href="http://website.come/folder/file.php?id=30&ajax=true">3</a>
<a href="http://website.come/folder/file.php?id=10&ajax=true">11</a>

But I have two matches in the links list and I just want the first match. What should I add to the jquery code?

jsfiddle

Ahmednagar answered 16/7, 2013 at 9:32 Comment(0)
V
8

Try this :

$("a").filter("[href*='id=10']").first().css({color: 'red'});

And if you want, you can also do that :

$("a[href*='id=10']").first().css({color: 'red'});
Voe answered 16/7, 2013 at 9:35 Comment(1)
Won't this get every single result and then return the first? Probably bad performance if you have a million things, but not a big deal with two.Reposition
F
1

Try this

 $("a").filter("[href*='id=10']:first").css({color: 'red'});

Demo

Franciscafranciscan answered 16/7, 2013 at 9:35 Comment(0)
P
1

Use the psuedo class first:

$("a").filter("[href*='id=10']:first").css({color: 'red'});
Peag answered 16/7, 2013 at 9:35 Comment(0)
A
1

$("a").filter("[href*='id=10']:eq(0)").css({color: 'red'});

0 can be every int of course.

http://jsfiddle.net/ygFDM/

Adel answered 16/7, 2013 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.