Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 ``.

$('#external a').attr('target', '_blank');
<!DOCTYPE html>
  <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" title="no title" charset="utf-8">
  <title>Links Page</title>
    <li><a href="http://google.com" class="external">Google</a></li>
    <li><a href="http://yahoo.com" class="external">Yahoo</a></li>
  <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>

2 Answers

Tim Knight
Tim Knight
28,863 Points


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,605 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');


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