3

I would like to create foreignObject in SVG using pure javascript. I don't know why it doesn't work. My foreign object is in a <g> element. And inside it is a simple div.

I tried using "requiredExtensions" and "xmlns" I thought that my div was somewhere outside the window but i checked getBoundingClientRect().left; and it is not.

My code is here:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

<title>SVG TEST</title>
<style>

</style>
<script>
    function init(){
        var svg = document.getElementsByTagName('svg')[0]; //Get svg element
        svg.setAttribute("xmlns","http://www.w3.org/2000/svg");
        var g=document.createElementNS("http://www.w3.org/2000/svg", 'g'); //Create a g element in SVG's namespace
        g.setAttribute("x",0); //Set g dat
        g.setAttribute("y",0); //Set g dat
        svg.appendChild(g);

        var newNode = document.createElementNS("http://www.w3.org/2000/svg", 'foreignobject'); //Create a rect in SVG's namespace
        newNode.setAttribute("x",0); //Set rect data
        newNode.setAttribute("y",0); //Set rect data
        newNode.setAttribute("width","180"); //Set rect data
        newNode.setAttribute("height","80"); //Set rect data
        g.appendChild(newNode);

        var f=newNode;

        var newDiv = document.createElement('div');     
        var divIdName = "div_1";
        newDiv.setAttribute('id',divIdName);
        newDiv.innerHTML = "First";
        f.appendChild(newDiv);
    }   
  </script>
</head>

<body onload="init()">

    <svg id="svg" width="300px" height="300px"/>  

</body>
</html>

1 Answer 1

3

SVG is case sensitive so you must create a foreignObject element and not a foreignobject element.

There are some other minor things wrong too:

  • setting an xmlns attribute will do nothing
  • <g> elements don't have x and y attributes
  • x and y on foreignObject elements default to 0 so those can be omitted too
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.