/* get reference to the canvas */
const canvas = document.getElementById("svg_canvas");
/* setup an object with the attributes for each element we want to set */
const elements = [{
name: "square1",
type: "rect",
textContent: "mouse over",
attributes: {
id: "square1",
"data-target": "toggle-target",
x: 100,
y: 100,
width: 100,
height: 100,
fill: "blue",
class: "hovering-sq"
}
}, {
name: "happytext",
type: "text",
textContent: "mouse over",
attributes: {
x: 110,
y: 150,
fill: "cyan",
class: "toggle-target"
}
}, {
name: "square2",
type: "rect",
attributes: {
id: "square2",
x: 50,
y: 50,
width: 50,
height: 50,
fill: "red",
class: "target-sq hide toggle-target"
}
}, {
name: "textthing",
type: "text",
textContent: "howdy doodee",
attributes: {
id: "textthing",
x: 200,
y: 200,
fill: "green",
class: "hide me toggle-target"
}
}];
/* now using the object above create an element with the attributes */
elements.forEach((prop) => {
let el = document.createElementNS('http://www.w3.org/2000/svg', prop.type);
const attributes = prop.attributes;
if (prop.hasOwnProperty('textContent')) {
el.textContent = prop.textContent;
}
for (const attr in attributes) {
el.setAttribute(attr, attributes[attr]);
}
canvas.appendChild(el);
});
/* get the element we want to use for the mouse enter/leave */
const t = canvas.querySelector('.hovering-sq');
/* handle the event for enter/leave */
function handleEvent(event) {
const container = event.target.closest('svg');
const targets = container.dataset.toggletargets;
const hiders = container.querySelectorAll(targets);
hiders.forEach((el) => {
el.classList.toggle('hide');
});
}
/* set up the event handlers */
t.addEventListener('mouseenter', handleEvent);
t.addEventListener('mouseleave', handleEvent);
.hide {
display: none;
}
<svg id="svg_canvas" viewBox="0 0 1200 600" width="1200px" height="600px" xmlns="http://www.w3.org/2000/svg" data-toggletargets=".toggle-target"></svg>