Reputation: 1
I got a div with a links to gallery pictures which are generated by a script. There are -let say x numbers of links + 20 which are alwas generated by the script. So every of the link has a # and number. Like www.example.com/#1. So in a gallery I can have e.g 5 pictures which will have #1 #2 #3,etc and those 20 that are always generated with the number starting in this case from #6 #7 till 26#.
So my question is how to find with jQuery those last twenty url's and remove # from them.
Arek
Upvotes: 0
Views: 1891
Reputation: 63532
var start = $("div a").length - 21;
start = start < 0 ? 0 : start;
$("div a:gt(" + start + ")[href^='#']").each(function() {
var $a = $(this);
$a.attr("href", $a.attr("href").replace("#", ""));
});
working example: http://jsfiddle.net/958ea/2/
Explained
var start = $("div a").length - 21;
will set start
to the total number of a
tags minus 21. 20 + 1 since length is the total count but we need the 0-based index.
So if there were 500
anchor tags start
would be equal to 479
;
start = start < 0 ? 0 : start;
will reset start
to 0
if somehow there weren't 20 a
tags present. For this example this probably isn't necessary, but a nice check so things don't break.
Then we loop through the a
tags using this selector: "div a:gt(" + start + ")[href^='#']"
which is going to select all a
tags with an index greater than the value of start
(which in my example is index = 10 which is <a href="#11">
). Next it further filters on a
tags that start-with #
. This might also be unnecessary but is another good thing to check.
Finally the #
character in href
is replaced with the empty string ""
Upvotes: 3
Reputation: 38578
Building on the answer above you can simplify things a bit:
$.each(("div a[href^='#']").slice(-20), function() {
var $a = $(this);
$a.attr("href", $a.attr("href").replace("#", ""));
});
slice(-20) will grab the last 20 elements of the array.
Upvotes: 0
Reputation: 7518
Look at jQuery nth-child. Just from reading it should look something like
$('body > a:nth-child(n+20)').each(function() {
var _href = $(this).attr("href").replace("#","");
$(this).attr("href", _href);
});
Edit: Nevermind... this will select all links after the 20th link. Not what you want.
Upvotes: 0
Reputation: 69915
If you replace "#" with "" in an anchor it doesnt appear as a link in most of the browser. Try this
var lastAnchor = $("div a[href='#']:last"), count = 0;
while(count++ <= 20){
lastAnchor = lastAnchor.attr("href", "javascript:void(0)").prev("a[href='#']");
}
Upvotes: 0
Reputation: 1556
$("div > a").each(function() {
var linkURL = $(this).attr("href");
var newURL = linkURL.replace("#", "");
//Do something with newURL here.
//eg. to assign it the new url:
//$(this).attr("href", newURL);
});
This will target every div with anchor tags in it, so if you have more than one, give the div an id and target it like this instead
$("#theIdYouChose > a").each(function() {
});
Upvotes: 0