I’m trying to show the alt
text of images on the #show
div. I want to click an image and show its alt
in #show
, click another image and show its alt
and like that. How can i make it work?
<div id="IMGS">
<h2>1</h2>
<div><img src="img/frog.jpg" alt="this is a frog" height="100" /><p>0</p></div>
<div><img src="img/bird.jpg" alt="this is a bird" height="100" /><p>0</p></div>
<div><img src="img/Photoshop-01.jpg" alt="this ain't real" height="100" /><p>0</p></div>
<div id="show"></div>
</div>
5
Answers
Add a class for image (just a dummy one)
JavaScript
In this code, you add an event listener for each image:
Check the working fiddle: https://jsfiddle.net/gerardofurtado/2bkkr6g6/3/
You can get all images with .querySelectorAll() and attach click handlers on them as follows:
If you look at the console you will see that your code throws an error:
While NodeLists are theoretically iterable, no browser implements that yet afaik. Convert the list to an array first, then it will work:
Notes
textContent
.innerText
is actually IE.for...of
andlet
are a relatively new constructs that are not supported by every (especially older) browsers.There is no need for them though. You can access the clicked element via
this
inside the event handler, which eliminates the need for a block scoped variable.for...of
can be replaced by.forEach
:or make use of event delegation:
The easiest way to achieve that is through jQuery.
Here’s the code you need: