名前空間を指定して新しく要素を生成
名前空間を指定して新しく要素を生成するには、element.createElementNSメソッドを使用します。
構文
var newElement = element.createElementNS(namespace, element name);
引数
| 引数名 | 型 | 説明 | |
|---|---|---|---|
| 第一引数 必須 |
namespace | string | 名前空間のURI |
| 第一引数 必須 |
element name | string | 生成する要素名 |
戻り値
生成された要素を返します。
サンプルコード
JavaScript
var svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
circleElement = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
// svg要素の属性を設定
svgElement.setAttribute('viewBox', '0 0 100 100');
svgElement.setAttribute('width', '100');
svgElement.setAttribute('height', '100');
// circle要素の属性を設定
circleElement.setAttribute('cx', 50);
circleElement.setAttribute('cy', 50);
circleElement.setAttribute('r', 50);
svgElement.appendChild(circleElement);
document.body.appendChild(svgElement);
名前空間が必要な言語
element.createElementメソッドではなく、element.createElementNSメソッドで名前空間を指定する必要のある言語は、主に次の通りです。
| 言語 | 名前空間のURI |
|---|---|
| XHTML | http://www.w3.org/1999/xhtml |
| SVG | http://www.w3.org/2000/svg |
| MathML | http://www.w3.org/1998/Math/MathML |