Try the following. Note that it uses es6 functions
const images = Array.from( document.querySelectorAll('img') );
images.forEach(image => {
let alt = image.getAttribute('alt');
if( alt )
{
image.insertAdjacentHTML('afterEnd', `<p class="caption">${alt}</p>`);
}
});
<img src="https://placeimg.com/240/280/any" alt="These are planets">
<img src="https://placeimg.com/240/280/any" alt="These are something">
<img src="https://placeimg.com/240/280/any" alt="Something else">
<img src="https://placeimg.com/240/280/any" alt="Something">
solved Display Image alt text using vanilla Javascript