user3154898
user3154898

Reputation: 311

jQuery attr("href") doesn't work

I'm building a wordpress theme. At the bottom of the post I inserted a custom navigation bar where I display tags and pagination links. (all wordpress elements work fine: wordpress is not the problem that brought me here)

I would like to use the javascript method .load() to refresh the post content when I click on a page number link (Basically I want to navigate through the post's pages without reloading all the stuff at each time)

To do that, I need to retrive the href attribute of the link I want to load. After reading the official APIs and searched on several forums I'm trying to achieve that through this code... but it doesn't work and I can't get why.

The HTML

<nav id="tag-and-navigation">
    <div class="page-numbers tags-and-navigation-elem">
        <a href="my_first_page">1</a>
        <a href="my_second_page">2</a>
    </div>
</nav>

The jQuery (debugging mode version: I just try to display in the console the href)

$(document).ready(function(){
    $('.page-numbers.tags-and-navigation-elem').click(function(){
       console.log($(this).attr('href'));
    });
});

this code display "undefined" on the console, while I attend "my_first_page". Any clue? Thanks

Upvotes: 0

Views: 4240

Answers (3)

Mritunjay
Mritunjay

Reputation: 25882

That is because you are selecting a div using $('.page-numbers.tags-and-navigation-elem'), which doesn't have href attribute.

You might want to say

console.log($(this).find('a').attr('href'));

OR

If you want to click on anchors and get their hrefs use this

$(document).ready(function(){
    $('.page-numbers.tags-and-navigation-elem a').click(function(){
       console.log($(this).attr('href'));
    });
});

Upvotes: 4

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

Apparently your referenced element is not an anchor tag.

Your code:

$(document).ready(function(){
    $('.page-numbers.tags-and-navigation-elem').click(function(){
       console.log($(this).attr('href'));
    });
});

You could say:

$(document).ready(function(){
    $('.page-numbers.tags-and-navigation-elem a').click(function(){
       console.log($(this).attr('href'));
    });
});

Upvotes: 0

Mikkel Damm
Mikkel Damm

Reputation: 341

Your jquery selector Is selecting the div element and not the a tag. Therefor $(this) will be the div element.

Instead change your selector to this:

$('.page-numbers.tags-and-navigation-elem a')

Then it will work :)

Upvotes: 2

Related Questions