First you need to calculate the column number of td itself.
This is done by counting the number of tds to our td; accounting for colspan attributes:
function getElementColumn(td) { var tr = td.parentNode; var col = 0; for (var i = 0, l = tr.childNodes.length; i < l; ++i) { var td2 = tr.childNodes[i]; if (td2.nodeType != 1) continue; if (td2.nodeName.toLowerCase() != 'td' && td2.nodeName.toLowerCase() != 'th') continue; if (td2 === td) { return col; } var colspan = +td2.getAttribute('colspan') || 1; col += colspan; } }
You can then iterate over the col elements and return the number corresponding to the column number.
First we need to find the colgroup element. Then it is similar to calculating the column number td:
function getCol(table, colNumber) { var col = 0; var cg; for (var i = 0, l = table.childNodes.length; i < l; ++i) { var elem = table.childNodes[i]; if (elem.nodeType != 1) continue; if (elem.nodeName.toLowerCase() != 'colgroup') continue; cg = elem; break; } if (!cg) return; for (var i = 0, l = cg.childNodes.length; i < l; ++i) { var elem = cg.childNodes[i]; console.log(elem); if (elem.nodeType != 1) continue; if (elem.nodeName.toLowerCase() != 'col') continue; if (col == colNumber) return elem; var colspan = +elem.getAttribute('span') || 1; col += colspan; } }
With these two functions, you can do this:
var id = getCol(table, getElementColumn(td)).id;
http://jsfiddle.net/wHyUQ/1/
jQuery version
function getElementColumn(td) { var col = 0; $(td).prevAll('td, th').each(function() { col += +$(this).attr('colspan') || 1; }); return col; } function getCol(table, colNumber) { var col = 0, elem; $(table).find('> colgroup > col').each(function() { if (colNumber == col) { elem = this; return false; } col += +$(this).attr('span') || 1; }); return elem; }
http://jsfiddle.net/wHyUQ/2/
arnaud576875
source share