ceth
ceth

Reputation: 45295

Get HREF property

<a class="some" id="1" href="/s/1/2">link 1</a>
<a class="some" id="2" href="/s/2/3">link 1</a>

<script>
$(document).ready(function() {
    $('.some').click(function() {
        var id = this.id;
        var link = $(this).css('href');
        alert(id);
        alert(link);
        return false;
    });
});
</script>

When I click on the link I get correct id, but "undefined" link. What is the problem and how can I fix it?

Upvotes: 1

Views: 318

Answers (3)

Sarfraz
Sarfraz

Reputation: 382656

Use attr():

var link = $(this).attr('href');

Or simply:

var link = this.href;

Your code should look like:

$(document).ready(function() {
    $('.some').click(function() {
        var id = this.id;
        var link = this.href;
        alert(id);
        alert(link);
        return false;
    });
});

Upvotes: 1

Jan Hančič
Jan Hančič

Reputation: 53931

Change

var link = $(this).css('href');

to

var link = $(this).attr('href');

.css() is used to get/set CSS properties, .attr() is used to get/set attributes on elements.

Upvotes: 5

Ben Everard
Ben Everard

Reputation: 13804

You need to access the elements attribute, not CSS property :-)

var link = $(this).attr('href');

Upvotes: 1

Related Questions