My intention is to create class="dot" based on the number of elements in the array called count, then use the following for loop:
for(var i = 0; i < count.length; i++)
So what I want to get is a single <span class="dot" onclick="currentSlide(1)"></span> where the currentSlide argument is automatically updated based on the for loop, therefore having i in place of 1,2,3 etc.
Is it possible to do this? Can you help me? I'm new to html and javascript.
<script>
var slideIndex = 1;
showSlides(slideIndex);
function currentSlide(n) {
showSlides(slideIndex = n);
}
var count = ['img1','img2','img3','img4']
</script>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
This should work by using template literal.
var slideIndex = 1;
//showSlides(slideIndex);
function currentSlide(n) {
showSlides(slideIndex = n);
}
var count = ['img1', 'img2', 'img3', 'img4']
for (var i = 0; i < count.length; i++) {
document.querySelector('div').innerHTML += `
<span class="dot" onclick=currentSlide(${i})></span>
`
}
console.log(document.body.innerHTML)
<div style="text-align:center">
<!--
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
-->
</div>
var slideIndex = 1;
//showSlides(slideIndex);
function currentSlide(n) {
showSlides(slideIndex = n);
}
var count = ['img1', 'img2', 'img3', 'img4']
for (var i = 0; i < count.length; i++) {
document.body.innerHTML += `
<span class="dot" onclick=currentSlide(${i})></span>
`
}
console.log(document.querySelectorAll('span'))
<div style="text-align:center">
</div>