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

Run
  • 54,938
  • 169
  • 450
  • 748

4 Answers4

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'});
Lucas Willems
  • 6,673
  • 4
  • 28
  • 45
  • 8
    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. – Andrew May 20 '15 at 17:14
  • Agreeing with Andrew! Imagine, instead, you're selecting records from a database. Do you query for every record in a table and THEN run conditions against them all? No. You write your SQL with as many conditions as necessary to efficiently get the results you need. THEN, you iterate over the result-set to process them. The same true with jQuery/JS. Your initial selection should be specific. Use an element id, if possible, or perhaps a parent element's id and then an html tag descendant, and this greatly optimizes the jQuery selection, making it faster and less wasteful. – Troy Niemeier Jan 20 '23 at 21:48
1

Try this

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

Demo

Amit
  • 15,217
  • 8
  • 46
  • 68
  • When using jQuery, in general, outside of this contrived example, DO NOT select an html tag from the entire DOM. Select an id, or a parent's id and then specify the element you're targeting within that parent element. Also, don't repeatedly jQuery select the same things in the same scope. Put your jQuery objects in variables for re-use, if applicable. It's really wasteful to have `$(this)....` referenced 12+ times in the same event handler scope. – Troy Niemeier Jan 20 '23 at 21:53
1

Use the psuedo class first:

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

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

0 can be every int of course.

http://jsfiddle.net/ygFDM/

Pieter
  • 1,823
  • 1
  • 12
  • 16