Search code examples
javascriptsvgline

Reimplementation of svg line not functioning


I've drawn a line before with this exact code but when reimplementing it into another project something isn't working.

let main = document.getElementById('main');
let svg = document.createElement('svg');
let newLine = document.createElement('line');
svg.setAttribute('style', `position: fixed;display: block;`);

newLine.setAttribute('x1', 0);
newLine.setAttribute('y1', 0);
newLine.setAttribute('x2', 500);
newLine.setAttribute('y2', 500);
newLine.setAttribute('style', `stroke:red;stroke-width:100;`);
svg.appendChild(newLine);
main.appendChild(svg);

Before I was running an express server and JSDOM to fill a div in the document with svg's then sending the innerhtml of the document element as the body when routing to '/', not the most performant way to do it but I was just playing around around with tools we were learning in class. When I put the code below into my html a black line is displayed as it should so I feel I'm missing some small piece...

<svg width="500" height="500"> 
 <line x1="50" y1="50" x2="350" y2="350" stroke="black" />
</svg>

Solution

  • You need to use createElementNS when creating your svg and line elements, otherwise it just thinks they're made up tags and not actual SVG.

    Also, since you're not using variables in your setAttribute, you should avoid string interpolation and just use single-quotes instead of backticks.

    Solution

    let main = document.getElementById('main');
    let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    let newLine = document.createElementNS('http://www.w3.org/2000/svg','line');
    svg.setAttribute('style', 'position: fixed;display: block;');
    
    newLine.setAttribute('x1', 0);
    newLine.setAttribute('y1', 80);
    newLine.setAttribute('x2', 100);
    newLine.setAttribute('y2', 20);
    newLine.setAttribute('style', 'stroke:red;stroke-width:100;');
    svg.appendChild(newLine);
    main.appendChild(svg);
    <div id="main"></div>

    Documentation

    https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS