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

186
Visualizações
Get innerText + alt if have img

i have a span like

<span class="message">blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>

i want to get the text + the alt of image if are there

I have tried :

let el = document.getElementById(".message");
console.log(el.innerText)

but it return just the text, i want text + alt of img (as if we copy paste with the mouse on a browser)

Thanks

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

0

const spanText = document.querySelector(".message").textContent;
const spanImgAlt = document.querySelector(".message img").getAttribute("alt");

console.log("<span> Text:", spanText);
console.log("<img> alt:", spanImgAlt);
<span class="message">blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>


If you want to check for the presence of the span and img tags before accessing their content, here's the code for it:

const span = document.querySelector(".message");

if ( span ){

  console.log("<span> Text:", span.textContent);

  const spanImg = span.querySelector("img");

  if ( spanImg ){
    console.log("<img> alt:", spanImg.alt);
  }

}
<span class="message">blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Don't use getElementById. You want querySelector to use a CSS selector to pick up the element with the message class.

  2. Then use querySelector again on that element to find the image, and log the alt attribute.

const el = document.querySelector(".message");
const img = el.querySelector('img');
console.log(el.innerText, img.alt);
<span class="message">blablabla <img src="https://dummyimage.com/100x100/000/fff" alt="SAUTE" /></span>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can try this way :-

<span class="message">blablabla <img width="50px"
  src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" ></span>
let message = document.querySelector('.message').innerText
console.log(message)
let alt = document.querySelector('.message img').getAttribute('alt')
if(alt != null){
  console.log(alt)
}
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