文件:createElementNS() 方法
Baseline 廣泛可用 *
使用指定的名稱空間 URI 和限定名稱建立元素。
要建立不指定名稱空間 URI 的元素,請使用 createElement() 方法。
語法
js
createElementNS(namespaceURI, qualifiedName)
createElementNS(namespaceURI, qualifiedName, options)
引數
namespaceURI-
一個字串,指定要與元素關聯的
namespaceURI。一些重要的名稱空間 URI 是: qualifiedName(限定名稱)-
一個字串,指定要建立的元素的型別。建立元素的
nodeName屬性將使用 qualifiedName 的值進行初始化。 options可選-
一個可選的
ElementCreationOptions物件,其中包含一個名為is的屬性,其值是先前使用customElements.define()定義的自定義元素的標籤名稱。為了向後相容,一些瀏覽器允許您在此處傳遞一個字串而不是一個物件,其中字串的值是自定義元素的標籤名稱。有關如何使用此引數的更多資訊,請參閱擴充套件原生 HTML 元素。新元素將獲得一個
is屬性,其值為自定義元素的標籤名稱。自定義元素是僅在某些瀏覽器中可用的實驗性功能。
返回值
新的 Element。
異常
NamespaceErrorDOMException-
如果
namespaceURI值不是有效的名稱空間 URI,則丟擲此異常。 InvalidCharacterErrorDOMException-
如果
qualifiedName值不是有效的 XML 名稱,則丟擲此異常;例如,它以數字、連字元或句點開頭,或包含字母數字字元、下劃線、連字元或句點以外的字元。
示例
這將在 XHTML 名稱空間中建立一個新的 <div> 元素,並將其附加到 vbox 元素。儘管這不是一個非常有用的 XUL 文件,但它確實演示了在單個文件中使用來自兩個不同名稱空間的元素。
xml
<?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><![CDATA[
let container;
let newDiv;
let textNode;
function init() {
container = document.getElementById("ContainerBox");
newDiv = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
textNode = document.createTextNode(
"This is text that was constructed dynamically with createElementNS and createTextNode then inserted into the document using appendChild.",
);
newDiv.appendChild(textNode);
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 文件中是不推薦的。這個特定的示例實際上是一個嵌入 XHTML 的 XUL 文件,但是,該建議仍然適用。
規範
| 規範 |
|---|
| DOM # ref-for-dom-document-createelementns① |
瀏覽器相容性
載入中…