Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use a for loop in javascript to add HTML

I'm making a little gallery in my website and it contains lots of pictures, how can I use a for loop to add the li in my website.

This is my HTML right now and instead of all those <li> I would like a for loop. HTML:

<div id="pictureBlock">
    <div id="three-columns" class="grid-container">
        <ul class="rig columns-3">
            <li><img src="images/1.jpg" /></li>
            <li><img src="images/2.jpg" /></li>
            <li><img src="images/3.jpg" /></li>
            <li><img src="images/4.jpg" /></li>
            <li><img src="images/5.jpg" /></li>
            <li><img src="images/6.jpg" /></li>
            <li><img src="images/7.jpg" /></li>
            <li><img src="images/8.jpg" /></li>
            <li><img src="images/9.jpg" /></li>
            <li><img src="images/10.jpg" /></li>
            <li><img src="images/11.jpg" /></li>
            <li><img src="images/12.jpg" /></li>
            <li><img src="images/13.jpg" /></li>
            <li><img src="images/14.jpg" /></li>
            <li><img src="images/15.jpg" /></li>
        </ul>
    </div>
</div>
like image 305
Anona Avatar asked Dec 19 '22 05:12

Anona


2 Answers

Using jQuery:

var ul = $('ul.rig');
var count = 15; // number of images

for(var i = 1; i <= count; i++) {
    ul.append('<li><img src="images/' + i + '.jpg"></li>');
}
like image 57
Hamid Mohayeji Avatar answered Mar 01 '23 06:03

Hamid Mohayeji


<div id="pictureBlock">
    <div id="three-columns" class="grid-container">
        <ul class="rig columns-3" id="gallery">
        
        </ul>
    </div>
</div>

<script>
    var gal = document.getElementById('gallery');
    

    for (var i = 1; i < 15 ; i++) {
        gal.innerHTML += "<li><img src='images/" + i + ".jpg' /></li>";
    };

</script>
like image 20
theshemul Avatar answered Mar 01 '23 06:03

theshemul