S.p
S.p

Reputation: 1059

selecting closest anchor element using jquery

I have a table with one link as follows

 <td>
      <a href="#" class="topiclink">@item.Topic</a>
   </td>

I want to select data of @item.topic. I tried using

  $('.topiclink').click(function (e) {
  var val = $(this).closest('a');
        alert(val)
    });

and many others but nothing seems working in this case.Thank for the help.

Upvotes: 3

Views: 2432

Answers (4)

Vincent Decaux
Vincent Decaux

Reputation: 10714

A lot of errors in your code ! Your element is already a '.topiclink' class, so why do you want the closest element ? Just use $(this) to access your element. val() not return the html of the element, you should use $(this).html();

 $('.topiclink').click(function (e) {
    alert($(this).html()); 
 }

Upvotes: 0

KevinIsNowOnline
KevinIsNowOnline

Reputation: 773

If you're trying to get the value '@item.Topic' on click of the anchor or any anchor, that is, you may use below code:

$('a').click( function () {
   console.log($(this).text());
});

Upvotes: 2

Rab
Rab

Reputation: 35572

var val = $(this).text(); 

Is enough to get you that

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173612

What you've clicked is already an anchor, so:

$('.topiclink').on('click', function (e) {
    var val = $(this).text();
    alert(val);
}

I'm also using .text() here, because .val() should only be used on HTML input elements.

Upvotes: 4

Related Questions