HTML DOM insertBefore()メソッド
例
<ul>要素の最初の子要素の前に新しい<li>要素を挿入します。
var newItem = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
newItem.appendChild(textnode); // Append the text to <li>
var list = document.getElementById("myList"); // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]); // Insert <li> before the first child of <ul>
以下の「自分で試してみてください」の例をもっと見てください。
定義と使用法
insertBefore()メソッドは、指定した既存の子の直前に、ノードを子として挿入します。
ヒント:テキストを使用して新しいリストアイテムを作成する場合は、<li>要素に追加するテキストノードとしてテキストを作成してから、リストに<li>を挿入することを忘れないでください。
insertBeforeメソッドを使用して、既存の要素を挿入/移動することもできます(「その他の例」を参照)。
ブラウザのサポート
表の数字は、このメソッドを完全にサポートする最初のブラウザバージョンを示しています。
Method | |||||
---|---|---|---|---|---|
insertBefore() | Yes | Yes | Yes | Yes | Yes |
構文
node.insertBefore(newnode, existingnode)
パラメータ値
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object you want to insert |
existingnode | Node object | Required. The child node you want to insert the new node before. If set to
null , the insertBefore method will insert the newnode at the end |
技術的な詳細
戻り値: | 挿入されたノードを表すノードオブジェクト |
---|---|
DOMバージョン | コアレベル1ノードオブジェクト |
その他の例
例
<li>要素をあるリストから別のリストに移動します。
var node = document.getElementById("myList2").lastChild;
var list = document.getElementById("myList1");
list.insertBefore(node, list.childNodes[0]);