I have a basic html page that has three canvas elements all with unique id's. I have collected the elements into an array using javascript's document.querySelectAll('canvas'). If I do a function using for each on the array, I can see all the info BUT if I try to extract that info so I can split it and get the id value, it doesn't work. I have tried several things but nothing seems to work. Am I trying to do something that cannot be done?
!IMPORTANT!: This has to be done in vanilla javascript, not third party libraries are allowed of any kind. Its due to security reasons, and that's all I can say on it.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title> Canvas Graph </title>
</head>
<body>
<!-- the id here will be used to set the height of the canvas to be created -->
<div>
<canvas id="canvas1"></canvas>
</div>
<div>
<canvas id="canvas2"></canvas>
</div>
<div>
<canvas id="canvas3"></canvas>
</div>
</body>
</html>
<script>
document.onload = getCanvasId();
function getCanvasId() {
const elementList = document.querySelectorAll('canvas');
const elementArray = [...elementList];
var temp = [];
var stringArray = [];
elementArray.forEach(element => {
temp.push(element);
console.log(element);
});
for(i=0; i<temp.length; i ){
stringArray[i] = temp[i].toString();
console.log(stringArray);
}
temp.forEach(element => {
var t = element.toString().split("#");
console.log(t);
});
}
</script>
CodePudding user response:
I would recommend printing the html to console with console.dir()
to check the HTML DOM properties available for a particular element.
And you would access an id of an element using its id
property - Element.id.
const elementList = document.querySelectorAll('canvas');
var stringArray = [];
elementList.forEach(element => {
stringArray.push(element.id);
});
console.log(stringArray);
<div>
<canvas id="canvas1"></canvas>
</div>
<div>
<canvas id="canvas2"></canvas>
</div>
<div>
<canvas id="canvas3"></canvas>
</div>