Ano-Tech Computers
Enter keyword:

SVG+Javascript: Create new element
Problem:
How to generate a new SVG element such as circle, rect, line etc. using Javascript?
 
Solution:
// Create a new rectangle element
popup = document.createElementNS("http://www.w3.org/2000/svg", "rect");

// Set any attributes as desired
popup.setAttribute("x", posx);
popup.setAttribute("y", posy);
popup.setAttribute("width", 100);
popup.setAttribute("height", 200);
popup.setAttribute("class", "popup");
popup.setAttribute("onmouseup", "popup_mouseup(evt);");
popup.setAttribute("onmouseout", "popup_mouseout(evt);");

// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(popup);

 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles