Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Lightbox Adding New Attribute Values with attr()

John Bell
John Bell
1,333 Points

Opening a link in a new tab using JQuery

I'm trying to get all the links of a given class ('external') to open in a new tab. The error message from the Challenge Question is 'I was expecting target to be _blank not ``.

js/app.js
$('#external a').attr('target', '_blank');
index.html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
  <title>Links Page</title>
</head>
<body>
  <h1>Links</h1>
  <ul>
    <li><a href="http://google.com" class="external">Google</a></li>
    <li><a href="http://yahoo.com" class="external">Yahoo</a></li>
  </ul>
  <script src="//code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/app.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

2 Answers

Tim Knight
Tim Knight
28,888 Points

John,

You'll want to adjust the selector you're using. # let's you select IDs just like a CSS selector. You want to do something like this instead:

$('a.external').attr('target', '_blank');

Which would be every link with the class external.

John Bell
John Bell
1,333 Points

Thanks Tim. Much appreciated.

Sun-Li Beatteay
Sun-Li Beatteay
10,606 Points

The selector you're using in JQuery is selecting all the link ("a") tags inside of the id "external". Looking at your html, you have a link with the class of "external" but with no links inside it.

Therefore, your JQuery should look like what Tim wrote; with a "." instead of a "#" and with the "a" tag before the class name. If the "a" tag is confusing to you, you can just not use it, though it's a good habit to include it.

$('a.external').attr('target', '_blank');

OR

$('.external').attr('target', '_blank');