Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Get Value Using a Selector

Tags:

html

jquery

dom

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.

like image 913
Ryan Avatar asked Sep 24 '10 19:09

Ryan


4 Answers

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.

like image 186
Vivin Paliath Avatar answered Sep 29 '22 18:09

Vivin Paliath


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");
like image 23
Aaron Avatar answered Sep 29 '22 18:09

Aaron


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");
like image 21
AutoSponge Avatar answered Sep 29 '22 19:09

AutoSponge


Are you using this syntax by chance in a script tag in your page?

$(document).ready(function(){
   // Your code here
 });
like image 37
jcolebrand Avatar answered Sep 29 '22 18:09

jcolebrand