Michiel Roos
Michiel Roos

Reputation: 883

How can I set a viewBox on an SVG element created with JavaScript?

When I use a setAttribute('viewBox') on an SVG element that already exists in the DOM, it gets set properly (with an uppercase 'b').

When I create an SVG element in JavaScript and add the 'viewBox' attribute there . . . it ends up in the DOM in all lowercase letters.

Why is this?

document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20');

let svg = document.createElement('svg'),
  circle = document.createElement('circle');

circle.setAttribute('cx', 200);
circle.setAttribute('cy', 200);
circle.setAttribute('r', 10);
svg.setAttribute('viewBox', '190 190 20 20');
svg.appendChild(circle);
document.body.appendChild(svg);

// document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg {
  border: 2px dashed #666;
  width: 200px;
  height: 200px;
}
<p>Existing svg with dynamically added viewBox attribute:</p>
<div id="circle">
  <svg>
    <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" />
  </svg>
</div>

<p>Generated svg with dynamically added viewBox attribute:</p>

Upvotes: 5

Views: 5064

Answers (2)

Robert Longson
Robert Longson

Reputation: 124229

You're not creating a valid SVG element in the first place though. You can't use createElement to create SVG elements (that's only for HTML elements). You must use createElementNS and provide the SVG namespace as the first argument.

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

Upvotes: 3

MeTe-30
MeTe-30

Reputation: 2542

You have to use document.createElementNS("http://www.w3.org/2000/svg", "svg") instead of document.createElement('svg')

document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20');

let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"),
  circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");

circle.setAttribute('cx', 200);
circle.setAttribute('cy', 200);
circle.setAttribute('r', 10);
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.setAttribute('viewBox', '190 190 20 20');
svg.appendChild(circle);
document.body.appendChild(svg);

// document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg {
  border: 2px dashed #666;
  width: 200px;
  height: 200px;
}
<p>Existing svg with dynamically added viewBox attribute:</p>
<div id="circle">
  <svg>
    <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" />
  </svg>
</div>

<p>Generated svg with dynamically added viewBox attribute:</p>

Upvotes: 9

Related Questions