Home > Software design >  Collect a specific attribute from the last appearance of an element
Collect a specific attribute from the last appearance of an element

Time:09-30

function refresh_images() {
    if (!document.images) return;
    const totalimages = document.querySelectorAll("img").length;
    const lastimages = document.getElementsByTagName('img')[totalimages].getAttribute('name').replace("grafico-betfair-", "");
}

enter image description here

I'm trying to collect the element called name="grafico-betfair-5" but it returns an error saying:

Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute') at refresh_images

What should I change in my code so I can retrieve the value?

CodePudding user response:

You can get the last image by using the last index which you can get by deducting 1 from the length of the NodeList.

And also, as String.prototype.replace() method does not change the calling String object. It returns a new string, you need to set the attribute with the new name.

Demo:

//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"/>

  • Related