Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

174
Views
Creating a mutable SVG with Javascript

I would like to create a resizable SVG using JavaScript. If you run the code, you'll notice the "svgTriangle[0].innerHTML = "<polygon points='";" line does not get appended inside the SVG tag. If someone could help me figure out why this is not getting appended, I would greatly appreciate it. Thanks.

var svgTriangle = document.getElementsByClassName("svg-triangle");
var bgTrianglePoints;

function updateOnResize() {
  bgTrianglePoints = [
    [0, 0],
    [window.innerWidth * 0.76, 0],
    [window.innerWidth * .16, window.innerHeight * 1.2],
    [0, window.innerHeight * 1.2]
  ];

  svgTriangle[0].innerHTML = "<polygon points='";
  for (var i = 0; i < bgTrianglePoints.length; i++) {
    svgTriangle[0].innerHTML += bgTrianglePoints[i][0] + "," + bgTrianglePoints[i][1] + " ";
  }
  svgTriangle[0].innerHTML += "'/>";
}

window.onresize = function() {
  updateOnResize();
}

updateOnResize();
html,
body {
  margin: 0px;
  padding: 0px;
}

#header {
  width: 100vw;
  height: 85vh;
}

.svg-triangle {
  width: 100%;
  height: 100%;
  fill: red;
}
<div id="header">
  <svg xmlns="http://www.w3.org/2000/svg" class="svg-triangle"></svg>
</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To answer your question, why the first line does not appear in the HTML, it is probably because it makes the HTML invalid. You could instead use the document.createElementNS method as follows:

const polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");

to create the polygon element in the SVG namespace.

Then, you can create the string for the points attribute:

let points = "";

for (var i = 0; i < bgTrianglePoints.length; i++) {
    points += bgTrianglePoints[i][0] + "," + bgTrianglePoints[i][1] + " ";
  }

and finally set the attribute on the element:

polygon.setAttribute("points", points);

Now, you can use svgTriangle.appendChild(polygon) to add the polygon to the HTML.

Another possibility is to use the points property on the polygon element, which is an SVGPointList and use appendItem on it in a loop to add the points, but that is quite much code and not really necessary. Also, SVGPoint is already deprecated...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!