Reputation: 3
How do I select only the first instance of a link containing a specific href
, the solution can be css or javascript, I would prefer css as I need to make styling changes once I have selected the right link but I'm not even sure css can do what I need.
<ul class="digital-downloads">
<li> <a href="order_5129865a7d832&download_file=936">Link</a></li>
<li> <a href="order_5129870f01410&download_file=936">Link</a></li>
<li> <a href="order_512a033229f68&download_file=935">Link</a></li>
<li> <a href="order_512a048548f68&download_file=935">Link</a></li>
<li> <a href="order_512a0c31734a6&download_file=932">Link</a></li>
</ul>
As you can see by the code above, the first two links aren't identical but they have the same ending. I need a way to select only the first instance of a link containing download_file=936
or download_file=935
or download_file=932
etc.
The number of li's will always be different as well as the number of same links so I can't select the third li for example as the link href
wont always be 935 on the third li
, it could be 936 or 932 depending on the situation.
Upvotes: 0
Views: 227
Reputation: 5479
Use Regex:
$(function() {
var count = 0;
$('a').each(function() {
var match = $(this).attr('href').match(/(.*download_file=\d+)/);
if (match !== null && count == 0) {
alert(match.pop());
count++;
}
});
});
Upvotes: 0
Reputation: 664548
You can apply a filter against a jQuery selection, looping over them while comparing against the href from before:
var last;
var firsts = $(".digital-downloads li a").filter(function(){
var link = this.href.match(/download_file=\d+$/)[0];
if (link == last)
return false; // we had this before, don't select
else {
last = link;
return true; // we've found a new one!
}
});
In short and taking care of mismatched regex:
…
var m = this.href.match(/download_file=\d+$/);
return m && m[0] != last && (last=m[0],true);
…
Upvotes: 2
Reputation: 11461
$('a[href*="download_file=935"]:first')
To do it in just CSS gets really complicated.
Upvotes: 0
Reputation: 253318
Using JavaScript:
var first = document.querySelector('a[href$="936"]');
first.className = 'first';
This approach adds a CSS class-name in order to allow CSS styling, so should combine the benefits of each approach, so long as the browser supports document.querySelector()
.
Upvotes: 0