Home > front end >  Get innerText alt if have img
Get innerText alt if have img

Time:04-10

i have a span like

<span >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

CodePudding user response:

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 >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 >blablabla <img src="smileys/saute.gif" alt="SAUTE"></span>

CodePudding user response:

  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 >blablabla <img src="https://dummyimage.com/100x100/000/fff" alt="SAUTE" /></span>

CodePudding user response:

First of all the span element does not have any ID, it has a class so you can target it via querySelector:

document.querySelector('.message') Note that querySelector returns the first element it finds, querySelectorAll returns an array of found elements.

Then you can use the element you found and go the the firstElementChild / or use children[0] (the index of the child).

You can even use: document.querySelector('.message > img') to target the image.

const el = document.querySelector('.message');
cosnole.log("Inner text: ", el.innerText);
const img = el.firstElementChild;
console.log("Img alt: ", img.alt);

CodePudding user response:

You can try this way :-

<span >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)
}
  • Related