Happy
Happy

Reputation: 891

jQuery find by value

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?

Upvotes: 3

Views: 12474

Answers (5)

Chris Conway
Chris Conway

Reputation: 16519

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");
}

Upvotes: 1

Andy E
Andy E

Reputation: 344675

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.

Upvotes: 2

jAndy
jAndy

Reputation: 236092

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.

Upvotes: 4

Claudio Redi
Claudio Redi

Reputation: 68440

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")

Upvotes: 2

meo
meo

Reputation: 31249

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/

Upvotes: 7

Related Questions