Note: この記事は、3年以上前に書かれています。Webの進化は速い!情報の正確性は自己責任で判断してください。
JavascriptでHTML中に「何か」を挿入したい場合、InsertAdjacent系メソッドは凄く便利。でもFirefoxは未対応(IEやOperaは対応している)。「なんとかならないかな~」といろいろ探していたら、別件の調査中にたまたま使える方法を見つけたので、InsertAdjacent系メソッドのまとめと共にメモっておきます。
書式
object.insertAdjacentElement('type',oElement)object.insertAdjacentHTML('type','HTML')object.insertAdjacentText('type','text')
- 第一引数(type)
-
- 開始タグの前に設置 → beforeBegin
- 終了タグの前に設置 → beforeEnd
- 開始タグの後に設置 → afterBegin
- 終了タグの後に設置 → afterEnd
- 第二引数(oElement,HTML,text)
-
- oElement → オブジェクト
- HTML → 文字列
- text → テキストノード
memo: typeをシングルクオーテーションで囲うことは忘れがちなので、注意しよう。
Script
下記のコードを読み込めば、FirefoxでもInsertAdjacent系メソッドを使用できる。
if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){switch (where.toUpperCase()){case 'BEFOREBEGIN':this.parentNode.insertBefore(parsedNode,this)break;case 'BEFOREEND':this.appendChild(parsedNode);break;case 'AFTERBEGIN':this.insertBefore(parsedNode,this.firstChild);break;case 'AFTEREND':if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);else this.parentNode.appendChild(parsedNode);break;}}HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr){var r = this.ownerDocument.createRange();r.setStartBefore(this);var parsedHTML = r.createContextualFragment(htmlStr);this.insertAdjacentElement(where,parsedHTML)}HTMLElement.prototype.insertAdjacentText = function(where,txtStr){var parsedText = document.createTextNode(txtStr || '')this.insertAdjacentElement(where,parsedText)}};
参照
- openWebWare, openWYSIWYG
- Thousand Years, insertAdjacent.js
Note: スパム対策が面倒なので、コメント投稿を廃止しました。以前のコメントは残します。
ご意見・ご要望はtwitter@sigwygかはてブコメントにて。