Jquery filter: get only the first match?

I want to find a match in the url, and then do something on that link, for example, change the color, 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 list of links, and I just want the first match . What should I add to jquery code?

jsfiddle

+4
source share
4 answers

Try the following:

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

And if you want, you can also do this:

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

try it

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

Demo

+1
source

First use the psuedo class:

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

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

0 can be every int , of course.

http://jsfiddle.net/ygFDM/

+1
source

Source: https://habr.com/ru/post/1491608/


All Articles