I'm trying to figure out how to add an alt-text
attribute to an image by assigning a data attribute to the parent container of that image.
Basically, whatever text I add to data-alt
, will be assigned as alt-text
on the img element.
How can I write the attribute so that it's applied as alt-text
to the image, and not the parent?
What I want to enter in my code editor:
<div class="image-parent" data-alt="hello world">
<img src="path/to/image">
</div>
My desired result:
<div class="image-parent">
<img src="path/to/image" alt="hello world">
</div>
Here's what I've tried, but I'm not understanding how to apply the data attribute to the child element of image.
let imgParentContainers = document.querySelector('.image-parent');
let dataAlt = imgParentContainers.setAttribute('data-alt', '');
<div class="image-parent" data-alt="alt text here">
<img src="https://apkdoll.com/wp-content/uploads/2021/08/HOLLA-Live-Random-Video-Chat-MOD-APK.png">
</div>