Skip to content Skip to sidebar Skip to footer

How Can I Set An Attribute With Case-sensitive Name In A Javascript Generated Element

I create a svg element in javascript and I need to set an attribute which is case sensitive: viewBox. The element is created like this: var svgElem = document.createElement('svg');

Solution 1:

You need to create an actual svg element. When you do:

var svg = document.createElement('svg');

what you are actually getting is an HTML element named svg, not an SVG element. The key here is that SVG is not actually an HTML element at all, it is a foreign document root. To create an SVG element properly, you need to do

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

Specifically, this creates an XML element, rather than an HTML element. In the basic browser case,

document.createElement('div')

is the same as

document.createElementNS('http://www.w3.org/1999/xhtml', 'div');

This makes a big difference, because in HTML, attribute names are not case-sensitive, whereas in XML, they are. Also, if you were to append that SVG to the DOM, it would behave like a div since it is an unknown HTML element, rather than a real SVG element. An HTML parser is smart enough to create a foreign root node instead of an unknown HTML element, but your code is programmatic, so it can't do it automatically.

Solution 2:

It works fine for me in Chrome and Firefox.

var  svgns = "http://www.w3.org/2000/svg";

var  svg = document.createElementNS(svgns, "svg");
svg.setAttribute("width", "400");
svg.setAttribute("height", "400");

var  circle = document.createElementNS(svgns, "circle");
circle.setAttribute("cx", "300");
circle.setAttribute("cy", "300");
circle.setAttribute("r", "100");
svg.appendChild(circle);

document.getElementById("container").appendChild(svg);

// Now change the viewBox
svg.setAttribute("viewBox", "200 200 200 200");
<divid="container"></div>

(Note: updated to create the SVG from scratch as per OPs request)

Solution 3:

for HTMLElement, just change setAttribute("attrName", "value") to setAttributeNs(null,"attrName", "value") resolve my problem.

see this post :

'setAttributeNS()' doesn't convert the name to lower case.

Solution 4:

You should create the value using createAttribute, see Setting attribute value of an element in camelCase using a directive

var div1 = document.createElementNS("http://blabla/svg", "view");
var attr1 = document.createAttribute("viewBox");
attr1.value = "200 200 200 200";
div1.setAttributeNode(attr1);

Post a Comment for "How Can I Set An Attribute With Case-sensitive Name In A Javascript Generated Element"