I'm trying to select the first link on a page after the page has completely loaded and redirect the page to the link on the first page.
I understand how to use a selector, but I'm stumped as to how I can pick up the first item after the page loads. I'm assuming once I have the value I could use
window.location = "http://www.google.com/"
To then take the user to proper page once I have the dynamic link's value.
jQuery(document).ready(function() {
window.location = jQuery("a[href]:first").attr("href");
});
A selector with the :first
pseudo-class selects the first matched element. For more information on selectors, check out jQuery's excellent documentation.
EDIT
Actually ran my code and noticed that it was returning an empty string. This was because it was picking up the first a
tag which happened to not have an href
attribute. I've changed the selector to only select a
tags with an href
attribute.
For your selector, use a:first. This will give you the first anchor tag on the page. You can then set the location to the href attribute of the anchor tag.
Something like:
location = $("a:first").attr("href");
I'll point out that redirects are easily defeated. Don't rely on this for anything "secure."
You may also find that you need the first anchor that actually has an href:
$("a[href]:first").attr("href");
Are you using this syntax by chance in a script tag in your page?
$(document).ready(function(){
// Your code here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With