In JavaScript, Is assigning a class name to a regular element and a namespace element different?

Viewed 75
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

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();

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">

Related