Josh Randall
Josh Randall

Reputation: 1344

How to get href attribute for link with same class

I am new to jquery. I have link like this ..

<div>title 1<a href="/delete/1" class="del">Delete</a></div>
<div>title 2<a href="/delete/2" class="del">Delete</a></div>

jquery

  $(".del").click(function () {
     alert($(this).attr('href'));
     event.preventDefault();
  });

I am trying to get href attribute. But it says Object object. I am trying to figure out what I doing wrong. How I can fix this.

I appreciate any help.

Upvotes: 1

Views: 1177

Answers (4)

Bruno
Bruno

Reputation: 6000

The only thing that's wrong in your snippet is that you're referencing an event variable, that is not declared.

This work for me:

$(".del").click(function (event) {
	alert($(this).attr('href'));
	event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>title 1<a href="/delete/1" class="del">Delete</a></div>
<div>title 2<a href="/delete/2" class="del">Delete</a></div>

Upvotes: 1

IvanL
IvanL

Reputation: 2485

Seeing the comments and suggested answers I tried to isolate your issue using a single HTML page like this:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
    $('.del').click(function (event) {
        event.preventDefault();
        alert($(this).attr('href'));
    });
});
</script>
</head>
<body>
<div>title 1<a href="/delete/1" class="del">Delete</a></div>
<div>title 2<a href="/delete/2" class="del">Delete</a></div>
</body>
</html>

When testing this the code works perfectly fine. I also compared the .prop() vs the .attr() to see why people are suggesting this answer. Take careful note of the documentation of these 2 since swapping out one with the other isn't really problem solving for this case. The question author needs to provide a more specific testcase where the error occurs so we can provide a conclusive answer.

Upvotes: 0

Raul Rene
Raul Rene

Reputation: 10270

Use

alert($(this).prop('href'));

Upvotes: 2

netdjw
netdjw

Reputation: 5997

Maybe try this:

alert($(this).prop('href'));

Upvotes: 3

Related Questions