Tuesday, April 17, 2012

How to get anchor text/href on click using jQuery?


Consider I have an anchor which looks like this




<div class="res">
<a href="~/Resumes/Resumes1271354404687.docx">
~/Resumes/Resumes1271354404687.docx
</a>
</div>



NOTE: There won't be any id or class for the anchor...



I want to get either href/text in the jQuery onclick of that anchor.


Source: Tips4all

3 comments:

  1. Note: Apply the class info_link to any link you want to get the info from.

    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
    ~/Resumes/Resumes1271354404687.docx
    </a>


    For href:

    $(function(){
    $('.info_link').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
    });
    });


    For Text:

    $(function(){
    $('.info_link').click(function(){
    alert($(this).text());
    });
    });


    .

    Update Based On Question Edit

    You can get them like this now:

    For href:

    $(function(){
    $('div.res a').click(function(){
    alert($(this).attr('href'));
    // or alert($(this).hash();
    });
    });


    For Text:

    $(function(){
    $('div.res a').click(function(){
    alert($(this).text());
    });
    });

    ReplyDelete
  2. Edited to reflect update to question

    $(document).ready(function() {
    $(".res a").click(function() {
    alert($(this).attr("href"));
    });
    });

    ReplyDelete
  3. Updated code

    $('a','div.res').click(function(){
    var currentAnchor = $(this);
    alert(currentAnchor.text());
    alert(currentAnchor.attr('href'));
    });

    ReplyDelete