John
John

Reputation: 21927

jquery get target value for href

Using jquery how do I find out the target value of a href link. e.g. if my link was

<a href="someurl.com" id="the_link" target="_blank">link</a>

the target would be _blank

Upvotes: 3

Views: 19548

Answers (6)

Bungle
Bungle

Reputation: 19712

While the accepted answer is correct for the specific case shown in the OP's example, in a real-world scenario, it's entirely possible that a link's effective target won't be defined as an attribute of its anchor element.

For example, consider this basic HTML page:

<!doctype html>
<html lang=en>
  <head>
    <meta charset="utf-8">
    <title>Example</title>
    <base target="_blank">
  </head>
  <body>
    <a href="someurl.com" id="the_link">link</a>
  </body>
</html>

Due to the <base target="_blank"> element in the <head>, the link's target is _blank, but this:

$('#the_link').attr('target');

will return undefined because the link has no target attribute.

A more effective approach might be something like:

function getTarget($link) {
  var linkTarget = $link.attr('target'),
      baseTarget = $('base').attr('target');
  if (typeof linkTarget !== 'undefined') {
    return linkTarget;
  } else if (typeof baseTarget !== 'undefined') {
    return baseTarget;
  }
}       

console.log(getTarget($('#the_link'));

That will return the link's target if defined, otherwise the base target if defined, otherwise undefined.

Upvotes: 0

Gary Green
Gary Green

Reputation: 22395

I'll be different and teach you part-vanilla js by acting directly on the elements properties:

$('#the_link')[0].target;

If you're using jQuery >=1.6 you should be using .prop than .attr really

$('#the_link').prop('target');

Upvotes: 5

Arda
Arda

Reputation: 6916

Use attr()

alert($('#the_link').attr('target'));

Upvotes: 1

Town
Town

Reputation: 14906

Using attr()

$('#the_link').attr('target');

Example on jsfiddle.

Upvotes: 9

DanielB
DanielB

Reputation: 20230

Simply

$('#the_link').attr('target');

Upvotes: 1

BenWells
BenWells

Reputation: 327

$('a').attr('target')

Should do it

(jQuery .attr Documentation)

Upvotes: 0

Related Questions