2
function foo(){
  var svg = document.querySelector(".crusher");
  let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
  polygon.className = "polygon01";
  svg.appendChild(polygon);
}

function foo01(){
  let actualPolygon = document.querySelector(".polygon01");
  actualPolygon.style = "fill:red";
}

When I try to select the class name, and change the fill color, i'm receiving a cannot access style of null value, so the class name is not being assigned the way I would like it to. Any help would be awesome.

2 Answers 2

1

Try use setAttribute

function foo(){
  var svg = document.querySelector(".crusher");
  let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
  polygon.setAttribute('class', 'polygon01');
  svg.appendChild(polygon);
}

function foo01(){
  let actualPolygon = document.querySelector(".polygon01");
  actualPolygon.style = "fill:red";
}

foo()
foo01();

Sign up to request clarification or add additional context in comments.

Comments

0

Taking a look at the spec for the SVG namespace you provided, it says that className is deprecated and to use classList.

// create polygon and add class
let polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");
polygon.classList.add("polygon01");

// append to element
document.querySelector(".crusher").appendChild(polygon);

// reference polygon with querySelector and add fill:red style
let actualPolygon = document.querySelector(".polygon01");
actualPolygon.style.fill = "red";
console.log(actualPolygon.style.fill);
<div class="crusher">

3 Comments

Thank you, What made you think to check that update for SVG? Just wondering so I can try to self correct in the future.
Between us, that's the first time I've ever looked at a spec, which I only did because createElementNS(...).className looked weird compared to what we'd expect (an empty string, compare with document.createElement('a').className which returns ""). The polygon className property actually spits out a weird-looking object that looks like SVGAnimatedString {baseVal: "", animVal: ""}, and I don't actually know what's happening there. It was enough to make me see if they broke className somehow and sure enough, it's deprecated for this namespace.
It looks like an interface for changing classes on the fly during animations or something: developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedString. Feel free to explore it a bit if you're curious.

Your Answer

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