简体   繁体   中英

Convert an array of ['[object HTMLCanvasElement]'] into a string to get the element "id" so I can select a specific element on the web page

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM