Answer 1 is approved if you are using jQuery . Answer 2 is approved if you use "modern" browsers that support querySelectorAll
.
The second also has a drawback: it assigns all <td>
event listeners, which is a rather difficult approach. Your first attempt to put the event handler only on <tr>
is actually lighter (by the way, this is called event delegation ), but there is also one small down: you need to filter the correct element.
So, if you want to stick with the cross browser " vanilla javaScript ", you can try the following:
First put this
and event
as arguments to call your function: onclick="OpenAdPreview(event, this)"
, then change your OpenAdPreview
function to this:
function OpenAdPreview(event, that){ var e = event || window.event, elm = e.target || e.srcElement, allTDs = that.getElementsByTagName('td'); while (elm.nodeName.toLowerCase() !== 'td' && elm !== that) { elm = elm.parentNode;
that
provides a <tr>
where you can find all td
with getElementsByTagName
and then filter out.
Another (and best) way is to assign a class name to td
that you donβt want to click and filter with this: <td class="dont-touch-me"></td>
, and then in your code:
if ((' ' + elm.className + ' ').indexOf('dont-touch-me') < 0) { ...
This way your code is independent of your layout. Then it always saves to change the class names of your HTML markup, and your code still works as expected.
By the way: inline events are not a good way. Try to stick to traditional event handler assignments such as .addEventListener
, .attachEvent
or jQuery.on()
event handling. Thus, you also do not need to deal with this
, that
and event
.
Added JSFiddle: http://jsfiddle.net/5zxun/4/