Can't get the href value of an anchor tag with jQuery

2.5k Views Asked by At

I'm trying to get the href value of an anchor tag using jQuery, but the this keyword is not working as expected.

source code

Here is the result of the code in the console:

devtools console


The part of the code I have problem with:

$('#container a').click(() => {
    console.log(this);
    let link = $(this).attr("href");
    console.log("from jquery - " + link);
    //chrome.tabs.create({ url: link });
});

As you can see, the this keyword is pointing on the window object. This code is part of an extension I'm trying to build for Opera.

3

There are 3 best solutions below

3
user7637745 On BEST ANSWER

You are using an arrow function () => {..} instead of a regular function function () {...}, that's why your this didn't work as you've expected.

So instead of this:

$('#container a').click(() => { ... });

Use this:

$('#container a').click(function() { ... });

Your updated code:

$('#container a').click(function () {
    console.log(this);
    let link = $(this).attr('href');
    console.log(link);
})

OR with an arrow function:

$('container a').click(event => {
    let link = $(event.currentTarget).attr('href');
    console.log(link);
})

More on arrow functions:

4
agDev On

This will give you the href value

var href = $('a').attr('href');

Here is a sample to test here:

$(document).ready(function() {
  $("a").click(function(event) {
    var href = $(event.target).attr('href'); //this will give you the href value
    alert(href);
    event.preventDefault();
  });
});
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<a href="I'm the href value">this is a test link, click me</a>

0
Karan On

Don't use the arrow function (() => {}) use classic function declaration (function() {}). Arrow functions don't bind this to the current scope.

$("#container a").click(function(){
    console.log(this);
    let link = $(this).attr("href");
    console.log(link);
})

You can learn more about arrow functions here.