views:

477

answers:

2

I'd like my GreaseMonkey script to run a function whenever elements with a specific class are inserted into a page. What's the most idiomatic way of doing that?

If it helps, it's a <select> element that is being inserted.

+3  A: 

Can you do something with DOMNodeInserted?

scottm
Dang, beat me to it. This event is fired whether using DOM methods (appendChild et al) or innerHTML, and is fired in Opera as well, so it won't break portability of your userscript (if you care). Check out http://www.quirksmode.org/dom/events/tests/DOMtree.html
Ben Blank
Thanks, that worked. However I'm concerned that running my function on every insertion might slow things down. Is there any way I can tell the type of element that was inserted?
Sam Hasler
if you specify an argument for the function that is being called on DOMNodeInserted, that argument's 'target' property will be the node that a node is being inserted into. So, you could check the nodeType of that to see if it is the type you are looking for. I'm not sure if you can check the class..
scottm
Looks like DOMNode has a className property you could check on:http://www.howtocreate.co.uk/tutorials/javascript/domstructure
scottm
A: 

You can use DOMNodeInserted

This event is fired whether using DOM methods (appendChild et al) or innerHTML, and is fired in Opera as well, so it won't break portability of your userscript (if you care). Check out http://www.quirksmode.org/dom/events/tests/DOMtree.html

If you specify an argument for the function that is being called on DOMNodeInserted, that argument's 'target' property will be the node that a node is being inserted into. So, you could check the nodeType of that to see if it is the type you are looking for. DOMNode also has a className property you could check on. http://www.howtocreate.co.uk/tutorials/javascript/domstructure

Daniel X Moore