How make pictures appear with .lenght method?

Hello I was wondering what is wrong with my js code, Im trying to make the images with the same class appear using lenght and a loop.
https://codepen.io/josemon322/pen/mdyYoMx

var birdPic = document.getElementsByClassName(“birdPic”).length;
var birdCont = document.getElementById(“birdCont”);
function showBirdPics() {
var birdElement = document.createElement(“img”);
birdElement.className = “birdPic”; // Will Add Class Name
birdElement.src = “1.jpg”; // Will Add Image name
for (var i = 0, r = birdPic.length; i < r; i++) {
birdPic.style.display = “block”;
}
birdCont.appendChild(birdElement);
}

showBirdPics();

You have to call the function showBirdPics then it will start working.

I have trying to use your method on my codepen file but its no really working, also I have trying to find the solution myself but so far no success any advice? thanks

Jose many problems with the code. Read this:

Copy and paste this instead and see if it doesnt help you understand:
html:

<button onclick="showBirdPics()">display</button>
<div id="birdCont">
  <img class="birdPic" src="https://stmedia.stimg.co/ows_157235893649127.jpg?fit=crop&crop=faces" alt="">
  <img class="birdPic" src="https://store-images.s-microsoft.com/image/apps.25758.14302936925643487.4d207f31-f506-432a-b6bd-72a91caf91f8.4752c3f6-0871-4ac4-b6bf-8fb2e382c8ed?mode=scale&q=90&h=1080&w=1920" alt="">
  <img class="birdPic" src="https://cdn.zmescience.com/wp-content/uploads/2018/05/kingfisher-2046453_960_720.jpg" alt="">
  <img class="birdPic" src="https://www.sciencemag.org/sites/default/files/styles/inline_colwidth__16_9__479w/public/images/ss-bird_honeycreeper.jpg?itok=sASuJ2dg" alt="">
</div>

your css:
.birdPic { display: none; width: 150px; height: auto; margin: 10px; }

delete your script. Use this one instead:

var birdPic = document.getElementsByClassName("birdPic");
function showBirdPics() {
  for (let x of birdPic) {
    x.setAttribute("style", "display:block;");
}
}

1 Like

If you want to display images on button click you can like below or as suggested by @kravmaguy.

var birdPic = document.getElementsByClassName("birdPic");
function showBirdPics() {
    for (var i = 0; i < birdPic.length; i++) {
    
        birdPic[i].style.display = "inline-block";
    }
}

In the Html ,

<button onclick="showBirdPics()">display</button>

If still, it’ll not work please tell us briefly about the task you are doing.

1 Like