Is there a way to retrieve only the children added up-to a specific point. For example, I have created rect and circle
and I am executing fnTwo
before I have added a path
with the the hope that it returns only rect and circle
. But it returns all the children; e.g. rect, circle +path
; even though path was added after. Is there a way for me execute fnTwo
to get the children that were added up to that point in time.
const svg = document.querySelector('svg');
const svgns = "http://www.w3.org/2000/svg"
const element = ['rect', 'circle'];
//fn for append
const fnOne = (element) => {
const child = document.createElementNS(svgns, element);
svg.append(child);
}
//append all elements
for (const elements of element) {
const element = elements;
fnOne(element)
};
// get all the children elements **up to this point in time**
const fnTwo = (element) => {
const children = element.children;
//do something with the children
console.log(children); //brings all children added before + after
}
const children = fnTwo(svg);
//add a path to test if it is retrieved through fnTwo
const childThree = document.createElementNS(svgns, 'path');
svg.append(childThree);
<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">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<svg>
</svg>
</body>
</html>
The problem you are experiencing is because you return original "array" of children, what you need to do is to return a copy:
const svg = document.querySelector('svg');
const svgns = "http://www.w3.org/2000/svg"
const element = ['rect', 'circle'];
//fn for append
const fnOne = (element) => {
const child = document.createElementNS(svgns, element);
svg.append(child);
}
//append all elements
for (const elements of element) {
const element = elements;
fnOne(element)
};
// get all the children elements **up to this point in time**
const fnTwo = (element) => {
const children = [...element.children]; //shallow copy of the array
//do something with the children
console.log(children); //brings all children added before + after
}
const children = fnTwo(svg);
//add a path to test if it is retrieved through fnTwo
const childThree = document.createElementNS(svgns, 'path');
svg.append(childThree);
<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">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<svg>
</svg>
</body>
</html>