I am creating some svg elements with javascript
, e.g.
const svg = document.querySelector('svg');
// variable for the namespace
const svgns = "http://www.w3.org/2000/svg"
//assigning svg element attribute
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('width', '400');
svg.setAttribute('height', '200');
svg.setAttribute('viewBox', '0 0 400 200');
//make background
var fill1 = '#e6e6e6';
//var fill2 = 'transparent';
let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('width', '200');
bg.setAttribute('height', '200');
bg.setAttribute('fill', fill1);
// append the new rectangle to the svg
svg.appendChild(bg);
function createRect(a) {
//create element
var rect1 = document.createElementNS(svgns, 'rect');
rect1.setAttribute('class', 'cl' + a);
rect1.setAttribute('id', 'id' + a);
rect1.setAttribute('x', '10');
rect1.setAttribute('y', '20');
rect1.setAttribute('width', '30');
rect1.setAttribute('height', '30');
//rect1.setAttribute("rx", "20");
rect1.setAttribute('fill', 'red');
svg.appendChild(rect1);
};
//create an array from 1 to 5
var bigArray = [];
for (var i = 0; i < 5; i++) {
bigArray[i] = i + 1;
};
//create Rect for each element of the array
for (const el of bigArray) {
createRect(el);
}
//create group
var group = document.createElementNS(svgns, 'g');
group.setAttribute('class', 'allRect');
group.setAttribute('id', 'allRect');
svg.appendChild(group);
var x = document.querySelectorAll('[class^=cl]');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<svg>
</svg>
</body>
</html>
How can I ask javascript
to insert a custom selected elements document.querySelectorAll('[class^=cl]')
(all 5 Rects) in a group allRect