tags:

views:

48

answers:

5

There is a link with title and some value:

<a href="http://site.com/someid/" title="Use ctrl + >">next</a>

How to find this link and throw its href attribute to some variable?

+2  A: 
var some_variable = $("a:[title='Use ctrl + >']").attr("href")

check out jQuery slectors: http://api.jquery.com/category/selectors/

here is a working example: http://jsfiddle.net/SXqVt/

meo
how to check, is it present on this page?
Happy
and then create var
Happy
`if($("a:[title='Use ctrl + >']").length){var some_variable = $("a:[title='Use ctrl + >']").attr("href")}`
meo
@Happy, @meo: the `if` statement there isn't necessary (and it's a bit inefficient to use the same selector twice), if jQuery doesn't find the `<a>` element, it returns an empty wrapper so the example given in the answer is good enough. It's also bad practice to define a variable inside an `if` block and refer to it outside the `if` block.
Andy E
thx for this. But i was just answering his question, i would not use the if to. But check if the variable is empty before i use it. Next time i try to be more precise in my answering.
meo
+2  A: 

I'd recommend you to add a class or an id to your anchor if possible. It's not very nice to find a element by title

Something like this if you add a class

<a href="http://site.com/someid/" title="Use ctrl + >" class="myAnchor">next</a>

and the jquery code would be

var some_variable = $("a.myAnchor").attr("href")

... Or this, if you set an id

<a href="http://site.com/someid/" title="Use ctrl + >" id="myAnchorId">next</a>

and the jquery code would be

var some_variable = $("#myAnchorId").attr("href")
Claudio Redi
+2  A: 

You may just use a contains selector like

$('a[href*="Use ctrl"]')

or maybe even more specific with =.

Anyway this seems not to be a good pratice, so you should think about other possibilitys to get that anchor. Maybe it has a unique parent which you can select by id or class. Even if you have to chain a little bit by using .find(), .closest() etc.

Thats a better way to go.

jAndy
+2  A: 

You can use the :contains() selector to find elements that contain a particular string of text:

alert($('a:contains(next)').attr('href'));

Be aware that this could also find elements that contain the word "next" anywhere, so it's best to make your selector as specific as possible, or provide the context argument to the jQuery function.

Andy E
+1  A: 

to answer your comment for meo's answer, you could do this:

var hrefValue;
if($("a:[title='Use ctrl + >']").length > 0)
{
    hrefValue = $("a:[title='Use ctrl + >']").attr("href");
}
Chris Conway