0

I am referring to one of the SOF answers for sorting the alphabets in second column using javascript, here is the example http://jsfiddle.net/mLYch/159/ .

In JS side it has getElementById and calling HTML tag with id

 <table id="caltbl">

 var tbl = document.getElementById("caltbl").tBodies[0];

I tried the same with the class and it doesn't work.

 <table class="caltbl">

 var tbl = document.getElementsByClass('caltbl').tBodies[0];

Can someone please assist on how to use make the script run without ID ?

Prime
  • 3,530
  • 5
  • 28
  • 47

2 Answers2

1

User .querySelector instead if you only want the first one.

var tbl = document.querySelector('.caltbl > tbody');

Or if you want multiple, use a loop with .querySelectorAll.

var tbls = document.querySelectorAll('.caltbl > tbody:first-of-type');
for (var i = 0; i < tbls.length; i++) {
  var tbl = tbls[i];
  // ...
}

Or you can use the loop with .getElementsByClassName if you prefer.

spanky
  • 2,768
  • 8
  • 9
0

document.getElementsByClass returns an array (since there can me more than one element with that class), so you'd have to change your code to

var tbl = document.getElementsByClass('caltbl')[0].tBodies[0];
Manuel Otto
  • 6,410
  • 1
  • 18
  • 25