Search code examples
htmljquerylistclassinnerhtml

Several Elements with same Classes . but i can get only first one , why?


i have several tables with same class names , these tables are created from php code via loop . like this

<?php 
$tableCount = 100;
$i=rand(1,999);
for ($i = 1; $i <= $tableCount; $i++) {
echo "<table class='tables'>";
echo "<tr class='myTr'>";
echo "<td  class='myTD'>";
echo $i;
echo "</td>";
echo "</tr>";
echo "</table>";
}

so we have 100 tds with different content , the problem for me is here : when the loop creates on page . and when i want to get all innerHtml or html() of all Td's class the compiler brings me first html() of td .

my jquery code :

var getclass = $(".myTD").html();

when i want to change the contents or remove or somethings ; i can do this. for example : for changing all contents of all td's with same class :

 $(".myTD").html("changed contents");

but i want to list . all html() of all td's with same class my output should be like this :

lists  outputs


  1,     14
  2,     188
  3,     20
  4,     2
  5,     99
  6,     11
  .,      .
  .,      .
  100,    73

and to end . but . my input gets me firs content ;

how can i solve that . plz :(

note this i want to do this with jquery or javascript. no php or server side .


Solution

  • Use .each() to loop.

    $(".myTD").each(function(i) {
        console.log(i, $(this).html());
    });