(function() {
var headings = document.getElementsByTagName('th');
for (var i = 0, amount = headings.length; i < amount; i++) {
headings[i].addEventListener("click", function() {
alert(this.innerText);
});
}
})();
Note I have changed the td
tags to th
tags because that is what it is. :-) Also note that I have used a generic getElementsByTagName('th')
call which should work for the HTML provided, but you may want to be more specific in a real HTML document.
Demo: http://jsfiddle.net/3G9Tx/
You may also want to look into console.log()
instead of using an alert()
, which is in most case easier / prefered.
UPDATE
An improved version:
function getTextFromHeading(e) {
var e = e || window.event,
target = e.target || e.srcElement,
text = target.textContent || target.innerText;
if (target.tagName.toLowerCase() === 'th') {
alert(text);
}
}
(function() {
var table = document.getElementsByTagName('table');
if (table[0].addEventListener) {
table[0].addEventListener('click', getTextFromHeading);
} else if (table[0].attachEvent) {
table[0].attachEvent('onclick', getTextFromHeading);
}
}());
This has some extra assignments to make sure it is cross browser compatible. It also only uses a single event handler.
Demo: http://jsfiddle.net/yRfem/