1

I was wondering if there was a way of adding JavaScript in every occurrence of a certain HTML tag, e.g.

<td onmousedown="">

At the moment I just have it in every single one of my td tags in my table, but there must be a cleaner way. Something like adding JavaScript in the way CSS adds formatting.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Acorn
  • 49,061
  • 27
  • 133
  • 172
  • what do you mean by "adding javascript"? Do you mean manipulating elements with javascript or adding script tags to elements? – hunter Apr 07 '10 at 18:21
  • 1
    I mean adding things like events to elements, which I assume are "script tags". (sorry, I'm an absolute beginner so don't know the terminology) – Acorn Apr 07 '10 at 18:24

3 Answers3

4

What your looking for is most likely "event binding." This can be done via your script rather than embedded in the HTML code. There are lots of different ways to accomplish such a task, here is one of them using "td" as in your example.

var items = document.getElementsByTagName("td");
for (var i=0; i<items.length; i++) {
  items[i].onmousedown = YourMouseDownFunction;
}
Greg W
  • 5,219
  • 1
  • 27
  • 33
2

You want jQuery. See http://jQuery.org This can be accomplished using a "selector" (jquery term)

1

Add an event listener (See also: Quirks Mode on events and on event listeners) to your document looking for mousedown events and filter it on the basis of the originating element.

There is a good answer here on Stackoverflow as well.

Community
  • 1
  • 1
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • Those are really useful links! I get the impression that the filtering method isn't ideal though as if you have a mouseover event then whenever you mouseover any element in the page it will check to see if it is an element that should trigger a function. – Acorn Apr 07 '10 at 19:55
  • @Acorn - I'm glad the links helped! And you are absolutely right about the filtering method, if you set the event listener on the `body`! I believe you could place the event listener on the `table` or `tbody` element, to reduce the amount of checking the browser would have to do. – Sean Vieira Apr 07 '10 at 21:41