How to Dynamically Add SVG Elements Without Using CreateElementNS

When woking with data visuallization on the web, we need to add data points dynamically. Then, in orde to add data points, we need to create svg elemets such as <circle>. We can't just use document.createElement(''circle") and append child to the parent svg. It just won;t work.

We need to use document.createElementNS(""http://www.w3.org/2000/svg"","circle");

<svg id="mySvg1">
</svg><script>
  var myPoint1 = document.createElementNS("http://www.w3.org/2000/svg","circle");
  myPoint1.setAttribute("cx","50");
  myPoint1.setAttribute("cy","50");
  myPoint1.setAttribute("stroke","black");
  myPoint1.setAttribute("r","20");
  mySvg1.appendChild(myPoint1);
</script>

What If I Don't Want to Usr the Weird Look CreateElementNS Code?

Yes, you can add svg element without using createElementNS. We need to use the good old innerHTML property of the svg tag. Consider the following code, it workds.
<svg id="mySvg2"></svg>
<button onclick="getNewDate()">Get New Date</button>
<script>
    function getNewDate(){
    mySvg2.innerHTML = "";  
    let i = 0;
    do {
      var randomx = Math.random()*100;
      var randomy = Math.random()*100;
      mySvg2.innerHTML += `<circle cx=${randomx} cy=${randomy} r="2" stroke="green" stroke-width="4" fill="yellow" />`;
      i++;
    }
    while (i < 100);
    };
</script>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser