Here’s a nifty little trick that allows you to write “contextual” JavaScript. It’s incredibly obtrusive and probably shouldn’t be used at all but it’s still a pretty cool idea:
<div id="some-div"> <script type=":contextual"> alert(this.id); // "some-div" is alerted </script> </div>
Instead of the this keyword referencing the global object (window) we can make it reference the parentNode of the script element. Here’s the code that makes it work:
(function(){ var scripts = document.getElementsByTagName('script'), script, i = 0; while ( (script = scripts[i++]) ) { if ( /:contextual$/.test(script.type) ) { (new Function(script.innerHTML)).call(script.parentNode); } } })();
Take it or leave it! – I’m indifferent either way – yes, it’s obtrusive but you’ve got to admit, contextual JavaScript looks pretty neat!