Thomas
Thomas

Reputation: 18

How to add a <svg> and subsequently a <polygon> element including attributes in HTML with javascript using the brower's DOM?

So, here's the code:

       <!doctype html>
        <html>
        <head>
        <script type="text/javascript">

        function stars() {

        var svg = document.createElement("svg");
        var polygon = document.createElement("polygon");


        polygon.setAttribute("style","width:70px;height:70px;")
        // A star with the vector points.
        polygon.setAttribute("points","10,1 4,19.8 19,7.8 1,7.8 16,19.8"); 
        // More properties.
        polygon.setAttribute("style","fill:yellow;stroke:yellow;stroke-width:1;fill-rule:nonzero;")
        // Put in the parent element.
        svg.appendChild(polygon);
        // Then again, put this parent element in an existing element, that is: "div".
        document.getElementById("littlediv").appendChild(svg);

    }

        </script>
        <style type="text/css">


        #littlediv
        {
        position:absolute;
        width:100px;
        height:100px;
        }

        svg
        {
        position:absolute;
        height:100px;
        width:100px;
        }

        polygon
        {
        position:absolute;
        height:100px;
        width:100px;
        }

        </style>
        </head>

        <body onload="stars()">

        <div id="littlediv">
        <!-- Here is where the created elements with it's attributes will append. -->
        </div>

        </body>
        </html>

When the page is loaded, the event-listener calls the function stars(). Then inside the function, the html elements svg and subsequently polygon are created, the polygon element is appended to svg, and again the svg element is appended to the existing element, that is: div.

Now, The elements and the accompanying style attributes will be neatly inserted into the div tags of that element. But, when inspecting, the elements and the attribute declarations won't show up in the page. So in CSS I've preset the dimensions for all of the elements to 100x100 px.

Of course you can copy/paste the code, save it with the .html suffix and inspect.

Did I do something stupid? Why won't the elements show up?

Upvotes: 0

Views: 1329

Answers (1)

John
John

Reputation: 3775

Change:

    var svg = document.createElement("svg");
    var polygon = document.createElement("polygon");

To:

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

    var svg = document.createElementNS(xmlns, "svg");
    var polygon = document.createElementNS(xmlns, "polygon");

The major difference is to use createElementNS() instead of createElement()

More details as to why... createElement vs. createElementNS

Upvotes: 1

Related Questions