DOM

Document.createElementNS() メソッド

 編集:2022.09.03 by T.A.

指定の名前空間 URI と修飾名を持つ要素を生成して返します。

名前空間 URI を指定せずに要素を生成する場合は、createElement() メソッドを使用してください。

構文
Document.createElementNS(namespaceURI, qualifiedName[, options])
Document 実質 document でしょう。
namespaceURI 文字列。要素に関連付ける を指定します。生成される要素の Node.namespaceURI プロパティは namespaceURI の値で初期化されます。下記の“重要な名前空間 URI” も参照してください。
qualifiedName 文字列。生成される要素の型を指定します。生成される要素の nodeName プロパティは、qualifiedName の値で初期化されます。
options 省略可。オブジェクト。任意の ElementCreationOptions オブジェクトで、is という名前の単一のプロパティを持ち、その値として以前に customElements.define() を使用して定義されたカスタム要素のタグ名を設定します。以前のバージョンの Custom Elements specification との後方互換性のため、ブラウザーによってはここにオブジェクトの代わりに、文字列を渡すことができ、その文字列の値はカスタム要素のタグ名になります。この引数の使い方について詳しい情報は、 を参照してください。

新しい要素には is 属性が与えられ、値はカスタム要素のタグ名になります。カスタム要素は一部のブラウザーのみで利用できる試行的な機能です。

返値

Element

重要な名前空間 URI
HTML http://www.w3.org/1999/xhtml
SVG http://www.w3.org/2000/svg
MathML http://www.w3.org/1998/Math/MathML
XUL http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul
XBL http://www.mozilla.org/xbl

これは新しい <div> 要素を XHTML 名前空間に生成し、vbox 要素に追加します。これは有用な XUL 文書ではありませんが、二つの異なる名前空間の要素を単一の文書内で利用する方法を紹介しています。

<?xml version="1.0"?>
<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
      xmlns:html="http://www.w3.org/1999/xhtml"
      title="||Working with elements||"
      onload="init()">

<script type="application/javascript"><![CDATA[
 let container;
 let newdiv;
 let txtnode;

 function init(){
   container = document.getElementById("ContainerBox");
   newdiv = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
   txtnode = document.createTextNode("This is text that was constructed dynamically with createElementNS and createTextNode then inserted into the document using appendChild.");
   newdiv.appendChild(txtnode);
   container.appendChild(newdiv);
 }

]]></script>

 <vbox id="ContainerBox" flex="1">
  <html:div>
   The script on this page will add dynamic content below:
  </html:div>
 </vbox>

</page>

上記の例は XHTML 文書では推奨されていないインラインスクリプトを使用しています。この部分的な例は実際には XUL 文書に埋め込んだ XHTML があるものですが、それでもこの推奨事項は適用されます。


テスト