f there's a collection of elements that need to be processed the same, it's best to use the class
attribute to target them.
Instead of targeting one element with: document.getElementById
, you get a NodeList
, which is a collection of elements, using document.getElementsByClassName
or document.querySelectorAll
.
Then, you need to loop through these elements and use the code you've already written.
Here's an example:
var imgs = document.getElementsByClassName('myImg');
for (var i = 0; i < imgs.length; i += 1) {
var img = imgs[i];
img.onclick = function() {
// your on click stuff
};
};
Don't forget to change the HTML to: class="myImg" src="imageone.jpg" alt="Image one" >
manpreet
Best Answer
2 years ago
So the above snippet is used in the modal image css3 tutorial. I understand i cannot have more than one tags with the same ID which is why the code online works with one image. After researching i know i have to use a dyamic ID with JS.
The previous JS line is what i need to change.
How does one dynamically change getElementById? So that i can use more then one with differentr src images?
Research shows Using a Tag selector or a class selector is inappropriate.
Any help documents to aid in my learning will be great as well.
So i made some nice progress with the css and stuff and it looks great. Now my next step is to use existing alts to include text when the modal appears. Below is the existing js line i had already
var captionText = document.getElementById("caption");
Now below is the html i will use when calling alt so that each image has its own alt text appearing under the modal pop up
I've tried it and doesnt seem to work, could it be my formatting in the css?