-1

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>
</tr>

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?

9
  • $('.DPtag > td:eq('+i+')').attr('id'); should work fine. what do $('.DPtag > td) returns? Commented Sep 12, 2016 at 12:19
  • First and second selector is right but third isn't. See jsfiddle.net/LgjoLc14
    – Mohammad
    Commented Sep 12, 2016 at 12:23
  • Please add more details to your question. Actually your could should work as expected. So there is something else wrong in your code ...
    – eisbehr
    Commented Sep 12, 2016 at 12:27
  • 3
    So you add a few KB of jQuery to reduce JavaScript? ;) Commented Sep 12, 2016 at 12:36
  • 1
    @epascarello: jQuery is loaded with or without my code so I do reduce ;)
    – m-arv
    Commented Sep 12, 2016 at 12:41

2 Answers 2

2

Note that at least in Chrome and Firefox it's not possible to select the <td> elements if they are 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;
  console.log(shorty);
}

Fiddle: https://jsfiddle.net/q3q076tn/

EDIT: Of course you could write it without jQuery as simple as exchanging:

var $td = $('.DPtag td');

with:

var $td = document.querySelectorAll('.DPtag td');

Important nodes: It's not a good idea to get the data like it's done in the question and in the accepted answer.

  1. You would reselect/search all the <td> elements in every single iteration of the loop. That makes it just unnecessarily slow.
  2. You use the name property for a <tr> tag which is not valid HTML. As already mentioned from CBroe. See also: https://developer.mozilla.org/en-US/docs/Web/API/Element/name This is why you should select it via class or ID.
1
  • Or in a more functional way: console.log($('.DPtag td').map(function (td) { return td.id }); Commented Sep 12, 2016 at 12:34
0

actually you don't need jQuery to write it more concisely:

document.querySelectorAll('[name=DPdays] td')[i].id

but if you prefer jQuery

$('[name=DPdays] td')[i].id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.