user944513
user944513

Reputation:

how to get text of anchor tag?

I have rows in li, inside li I have anchor tag. I want to get the value of that anchor tag. I am getting the id of li but I am not getting the value of the anchor tag.

<div class="testcaselist_row">
    <ul>
        <li id="tc_1" class="clickTestCaseRow">
            <a href="#" style="color: #ffffff!important;">aa</a>
            <a class="delete deleteTestCase_h"></a>
        </li>    
    </ul>
</div>
$(document).on('click', '.clickTestCaseRow', function (e) {
    var clickId = this.id;
    // getting the id
    alert($(this).closest('a').val()); // getting undefined
});

Expected aa value

Upvotes: 2

Views: 5663

Answers (4)

f1ames
f1ames

Reputation: 1744

In your context this is li element, you can write code as @Adil suggested or use e.target which is the element which caused event to trigger (in this case the anchor tag you need).

So: http://jsfiddle.net/VwqLQ/

html:

<div class="testcaselist_row">
    <ul>
        <li id="tc_1" class="clickTestCaseRow">
            <a href="#">aa</a>
            <a class="delete deleteTestCase_h"></a>
        </li>    
    </ul>
</div>

js:

$(document).on('click', '.clickTestCaseRow', function (e) {
    var clickId = this.id;
    console.log($(e.target).text());
});

Upvotes: 1

Anri
Anri

Reputation: 1693

use to find first() a tag and text() to get the content

first() returns first a tag inside li tag

see documentation http://api.jquery.com/first/

alert($(this).first('a').text());// getting undefine

OR

alert($('.clickTestCaseRow a').first().text());// getting undefine

Upvotes: 0

Adil
Adil

Reputation: 148180

You need find() instead of closest() and text() instead of val(). You want to find elements descendant of source of event find will get descendants on the other hand closest looks in ancestors.

The val() is used for input elements like textbox, checkbox etc. You need html or text for element like div, span, a etc.

Live Demo

 alert($(this).find('a').text());

To get the next element you can use eq(index) or next

Live Demo

$(document).on('click', '.clickTestCaseRow', function (e) { 
    alert($(this).find('a:eq(1)').text());
    //alert($(this).find('a').next().text());
});

Upvotes: 2

Shijin TR
Shijin TR

Reputation: 7788

Try

 alert($(this).find('a').html());

Insted of

 alert($(this).closest('a').val());

DEMO

Upvotes: -1

Related Questions