Benj Sanders
Benj Sanders

Reputation: 491

Selecting data out of the nth td element

I'm attempting to get the data("borgid") out of the following html:

<tr style="cursor:default;" class="odd">
    <td class=" ">1</td>
    <td class=" ">What was your favorite childhood pet's name?</td>
    <td data-borgid="1" class=" ">Generic Hospital Networks</td>
    <td class=" ">5173</td>
    <td style="text-align:right;" class=" "><input type="button" value="Remove" name="1" class="deleteMeCQ" style="cursor:pointer;"></td>
</tr>

I have tried both $(':nth-child(2)', $(this)).data("borgid") and $tds.eq(2).data("borgid"). Both return "undefined". Thanks in advance.

See also: Is there a way to combine $(this) with :nth-child?

var a = [];
$("#ChallengeQuestionsTable tbody tr").each(function () {

var $tds = $(this).children('td');

var questionid = '';
var question = '';
var borgid = '';

if ($tds.length == 5) {
    questionid = $tds.eq(0).html();
    question = $tds.eq(1).html();
    borgid = $(':nth-child(2)', $(this)).data("Borgid");

    a.push('{ "questionid" : "' + questionid + '", "question" : "' + question + '", "borgid" : "' + borgid + '" }');
}
});

Upvotes: 0

Views: 661

Answers (3)

collardeau
collardeau

Reputation: 820

Does this work, if you grab the data by an attribute selector?

var borgid = $(this).find("td[data-borgid]").data("borgid");

It could also be beneficial to avoid ":nth-child", shall you change your HTML later.

Upvotes: 0

Thomas Junk
Thomas Junk

Reputation: 5676

In general if you want to select the nth td you could go with

$("td:eq(1)")

e.g. to select the second td. If you want to iterate over all <tr> and its <td> and say, you want to select the 2nd one, you would do it as follows:

$("tbody").find("tr").each(function(){
    $(this).find("td:eq(1)").html("changed")
};

Here is a Fiddle to play with. And here is the documentation of :eq().

Upvotes: 0

juvian
juvian

Reputation: 16068

If you want to get borgid, you can select by existing attribute:

borgid = $($(this).find("[data-borgid]").get(0)).attr("data-borgid");

Upvotes: 1

Related Questions