3

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

John
  • 21,047
  • 43
  • 114
  • 155

6 Answers6

9

Using attr()

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

Example on jsfiddle.

Town
  • 14,706
  • 3
  • 48
  • 72
5

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');
Community
  • 1
  • 1
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • `$('#the_link')` is defintely not vanilla JavaScript. You want `document.getElementById('the_link').target`. – Town Jun 07 '11 at 10:26
1

Use attr()

alert($('#the_link').attr('target'));
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Arda
  • 6,756
  • 3
  • 47
  • 67
1

Simply

$('#the_link').attr('target');
DanielB
  • 19,910
  • 2
  • 44
  • 50
0

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.

Bungle
  • 19,392
  • 24
  • 79
  • 106
0
$('a').attr('target')

Should do it

(jQuery .attr Documentation)

BenWells
  • 317
  • 1
  • 10