0

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 + '" }');
}
});
Community
  • 1
  • 1
Benj Sanders
  • 481
  • 5
  • 15

3 Answers3

1

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

borgid = $($(this).find("[data-borgid]").get(0)).attr("data-borgid");
juvian
  • 15,875
  • 2
  • 37
  • 38
  • This technically works, I think I'm looking for something more like this (to use your code): $($(this).find("[data-borgid]").get(0)).data("borgid"); I was hoping for a more elegant solution than find() but this works. Thanks! – Benj Sanders May 19 '14 at 19:33
  • This solution got me closest to what I'm actually using in my code which is **borgid = $($tds.eq(2)).data("borgid");** – Benj Sanders May 19 '14 at 20:52
  • Great, just be careful of not changing the element's index if you are using that – juvian May 19 '14 at 22:44
  • Right. Yours is definitely a more dynamic solution but that's not as important at the moment. I was more concerned with a solution that is less of a load on the browser. I know it's not much but is still less. Thank! – Benj Sanders May 20 '14 at 19:29
0

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().

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
0

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.

collardeau
  • 800
  • 7
  • 13