MDN self-hosted library · e01.org

Document: createAttributeNS() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<p id="greeting">Bonjour!</p>
js
const el = document.getElementById("greeting");
const attr = document.createAttributeNS(
  "http://www.w3.org/XML/1998/namespace",
  "xml:lang",
);
attr.value = "fr";
el.setAttributeNode(attr);
html
<svg id="svg"></svg>
js
const svg = document.getElementById("svg");
const attr = document.createAttributeNS("", "viewBox");
attr.value = "0 0 100 100";
svg.setAttributeNode(attr);
console.log(svg.getAttribute("viewBox")); // "0 0 100 100"
js
svg.setAttribute("viewBox", "0 0 100 100");