Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!