documentcreateElementNS
document.createElementNS is a DOM method on the document object that creates an Element node in a specific namespace. It is used when constructing elements that belong to XML namespaces, such as SVG, MathML, or XHTML in XML-based documents. By providing a namespace URI, the created element is correctly associated with that namespace, which is important for proper namespacing and serialization.
Syntax: document.createElementNS(namespaceURI, qualifiedName)
- namespaceURI: a string containing the namespace URI for the element.
- qualifiedName: the element’s qualified name, which may include a prefix (for example, "svg" or "svg:g").
Return value: the newly created Element. If the combination of namespaceURI and qualifiedName is not valid
- The method is essential when creating elements belonging to non-HTML namespaces, such as SVG or MathML,
- In HTML documents, many developers use document.createElement for HTML elements. createElementNS is typically used for SVG,
- After creation, the element can be configured with attributes (including setAttributeNS) and appended to the document
Example: creating an SVG circle
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', '50');
circle.setAttribute('cy', '50');
circle.setAttribute('r', '40');
document.body.appendChild(circle);
See also: createElement, setAttributeNS, DOMException, Namespace.
---