view raw
m-arv m-arv - 8 months ago 105
HTML Question

jQuery get element by name

I wanna transform our javascript to jQuery due to necessary reduction of characters. This is my HTML & Javascript

var shorty = document.getElementsByName("DPdays")[0].getElementsByTagName("td")[i].id;

<tr class="DPtag" name="DPdays">
<td id="MO">&nbsp;</td>
<td id="DI">&nbsp;</td>
<td id="MI">&nbsp;</td>
<td id="DO">&nbsp;</td>
<td id="FR">&nbsp;</td>
<td id="SA">&nbsp;</td>
<td id="SO">&nbsp;</td>

I tried those:

var shorty = $('.DPtag > td:eq('+i+')').attr('id');
var shorty = $('[name=DPdays] > td:eq('+i+')').attr('id');
var shorty = $('[name=DPdays] > td:eq('+i+')').id;

But none works. How can I do that?


Note that at least in Chrome and Firefox it's not possible to select the <td> if it's not included in a <table> tag. Which is not valid HTML anyway if you don't do that. I assume that i is a variable in a loop to get all ids. In jQuery you could do it like that:

var $td = $('.DPtag td'); 
for (var i = 0; i < $td.length; i++) {
  var shorty = $td[i].id;