Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
Collect a specific attribute from the last appearance of an element
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda