Rápli András
Rápli András

Reputation: 3923

Get first cell in a row using JavaScript

Here's the first few lines of my code:

$('tr.existing_users > td').click(function(e){

    var target_name= e.target;
    var first_element=target_name.parent.first; //wrong

e.target gives me a td which is wrapped in a tr. I want to read the innerHTML of the first element in that tr row. How do I do this? (I'm also interested in jQuery solutions of course)

Upvotes: 0

Views: 1738

Answers (4)

Felix
Felix

Reputation: 38102

You can use closest() along with find() and :eq() selector:

$('tr.existing_users > td').click(function(e){
    var first_element =  $(this).closest('tr').find(':eq(0)').html();
});

Upvotes: 0

Barmar
Barmar

Reputation: 781058

var first_element = $(this).parent().children().eq(0);
var first_html = first_element.html();

Upvotes: 2

Kenny Thompson
Kenny Thompson

Reputation: 1492

$(e.target).closest('tr').children().first().html();

This solution keeps your existing click selector and will always give you the html of the first element within the first parent tr.

Upvotes: 0

epascarello
epascarello

Reputation: 207511

$('tr.existing_users').on("click", function(e){  //listen for click on tr
    console.log($(this).find("> td").eq(0).html());  //find children tds and get first one
});

Upvotes: 0

Related Questions