0 votes
in Image Classification by
Can you demonstrate how to alter the SVG DOM using JavaScript?

1 Answer

0 votes
by

Yes, JavaScript can be used to manipulate the SVG DOM. Here’s an example of how you might do this:

Firstly, we need to select our SVG element using JavaScript’s document.getElementById method.

let svgElement = document.getElementById('mySvg');

Next, we create a new circle element using document.createElementNS. The first argument is the SVG namespace and the second is the type of element.

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

We then set attributes for the circle such as cx, cy (center coordinates) and r (radius) using setAttributeNS. The first argument is null (no namespace), followed by attribute name and value.

newCircle.setAttributeNS(null, 'cx', 50);

newCircle.setAttributeNS(null, 'cy', 50);

newCircle.setAttributeNS(null, 'r', 20);

Finally, we append the new circle to our SVG element with appendChild.

svgElement.appendChild(newCircle);

...