function refresh_images() { if (!document.images) return; const totalimages = document.querySelectorAll("img").length; const lastimages = document.getElementsByTagName('img')[totalimages].getAttribute('name').replace("grafico-betfair-", ""); } Estoy tratando de recopilar el elemento llamado name="grafico-betfair-5" pero devuelve un error que dice:
Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute') at refresh_images¿Qué debo cambiar en mi código para poder recuperar el valor?
Puede obtener la última imagen utilizando el último índice que puede obtener restando 1 de la longitud de NodeList .
Y también, como el método String.prototype.replace() no cambia el objeto String que llama. Devuelve una nueva cadena , debe establecer el atributo con el nuevo nombre.
Manifestación:
//get all the images const totalImages = document.querySelectorAll('img'); //get the last image const lastImage = totalImages[totalImages.length - 1]; //get the new image name const lastImageName = lastImage.getAttribute('name').replace("grafico-betfair-", ""); //set the new name lastImage.setAttribute('name', lastImageName); //print the last image console.log(lastImage); <img name="test1" src="/img1.jpg"/> <img name="grafico-betfair-test" src="/img2.jpg"/>