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
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>
Don't use getElementById. You want querySelector to use a CSS selector to pick up the element with the message class.
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>
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)
}