Adrian: dynamisch erzeugtes svg wird im Browser nicht angezeigt

Hallo

ich habe folgendes Problem: Ich versuche mit js ein SVG zu erstellen. Hier das Dokument:

<!DOCTYPE html>
<html>
    <head></head>
    <body> 
    <script>
        const body = document.body
        const div = document.createElement("div")
        let h1 = document.createElement('h1')
        body.appendChild(div)
        div.appendChild(h1)
        h1.append('SVG Test')
    
        const mySVG = document.createElement("SVG")
        body.appendChild(mySVG) 
        mySVG.setAttribute('height', 500)
        mySVG.setAttribute('width', 500)
        path = document.createElement("path")
        mySVG.appendChild(path)
        document.querySelector('path').setAttribute('d', 'M 50,50 100,100 M100,50 150,100')
        document.querySelector('path').setAttribute('stroke', 'gold')
    </script>
 
</body>
</html>

Das Ergebnis im Browser (Safari):

<html><head></head>
    <body> 
    <script>
        const body = document.body
        const div = document.createElement("div")
        let h1 = document.createElement('h1')
        body.appendChild(div)
        div.appendChild(h1)
        h1.append('SVG Test')
    
        const mySVG = document.createElement("SVG")
        body.appendChild(mySVG) 
        mySVG.setAttribute('height', 500)
        mySVG.setAttribute('width', 500)
        path = document.createElement("path")
        mySVG.appendChild(path)
        document.querySelector('path').setAttribute('d', 'M 50,50 100,100 M100,50 150,100')
        document.querySelector('path').setAttribute('stroke', 'gold')
    </script><div><h1>SVG Test</h1></div><svg height="500" width="500"><path d="M 50,50 100,100 M100,50 150,100" stroke="gold"></path></svg>
 



</body></html

Das SVG wird also erstellt und eingefügt aber nicht angezeigt. Wenn ich den Code aber rauskopiere und direkt ins HTM einfüge wird das SVG angezeigt.

Hier wird das SVG angezeigt:

<html>
<head></head>
<body>
<div>
<h1>SVG Test</h1>
</div>
        <svg width="500" height="500"><path d="M 50,50 100,100 M100,50 150,100" stroke="gold"></path></svg> 
    
</body></html>

Warum wird das mit js erzeugte SVG nicht angezeigt, obwohl der Code dergleiche ist wie im statischen Dokument? Das js-erzeugte <div> und <h1> wird ja auch angezeigt.

Wenn mir da jemand weiterhelfen könnte, wäre sehr charmant.

akzeptierte Antworten

  1. Lieber Adrian,

    eine kurze Recherche ergab, dass Du hier einen Namespace verwenden musst:

    // Wert für Namespace 
    const svgNameSpace = "http://www.w3.org/2000/svg";
    
    const mySVG = document.createElementNS(svgNameSpace, "svg");
    const path = document.createElementNS(svgNameSpace, "path");
    

    Liebe Grüße

    Felix Riesterer

    1. Herzlichen Dank

      Das war genau das! Ich wäre da nie draufgekommen.

      Ich wünsche frohe Weihnacht

      Adrian