HTMLElement Prototyping 2007
HTMLElement Prototypingとは?
divやspanなどのHTML要素に独自メソッドを追加する為のprototype拡張の手法です。これを応用するとIEやOperaで採用されているinsertAdjacentHTMLをfxで利用できるようにしたりSafariで利用できるようになります。
各ブラウザ毎に実装が異なる場合があるのでクロスブラウザ用としてまとめエントリしておきます。
// prototype拡張前は当然以下はエラー document.getElementById('foo').foo(); // prototype拡張後は実行される。 HTMLElement.prototype.foo = function(){ alert('foo'); }; document.getElementById('foo').foo(); // alert('foo');
HTMLElement採用
HTMLElementがビルトインされている場合はそれを利用することでHTMLElement Prototypingできます。僕の確認できた範囲では以下のものは利用可能でした。Apolloで標準採用されていることに感激。HTMLElementが採用されている場合は簡単で以下のようにprototypeを拡張するだけで独自メソッドを追加できます。
HTMLElement.prototype.foo = function(){ }; HTMLElement.prototype.bar = function(){ };
Opera
7.0 | 8.0 | 9.0 |
---|---|---|
? | OK | OK |
Firefox
1.0 | 2.0 |
---|---|
OK | OK |
Konqueror
3.5.4以下 | 3.5.4 |
---|---|
? | OK |
HTMLElement非採用
HTMLElement非採用の困ったちゃんの対応です。
Safari1
Konqueror
document.createElement("html").constructorを辿ります。KonquerorはHTMLElementがある場合があります。
var Temp = document.createElement("html").constructor; HTMLElement = { prototype : Temp.__proto__.__proto__; };
Safari2
// おまじない document.createElement('html'); HTMLElement = { prototype : window["[[DOMElement.prototype]]"] || {}};