javascriptjquerybrowser-extensionopera-extension

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


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.


Solution

  • 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: