0

for(let n=0; n<5; n++){
  var elm = document.createElement('div');
  elm.setAttribute('class',"comments");
  document.getElementById('elm').appendChild(elm);

  var sec = document.createElement('div');
  sec.setAttribute('class', "sec");
  elm.appendChild(sec);

  var LPimg = new Image(); //document.createElement('img');
  LPimg.src = "C:\Users\Lenovo\Downloads\hacker8.jpeg";
  LPimg.setAttribute('class', "LP1");
  sec.appendChild(LPimg);
}
#elm{
          width: 90vw;
          height: 90vh;
          background: blue;
       }
       .comments{
         background: brown;
         width: 100%;
         height: 150px;
         border: 2px solid yellow;
       }
       .sec{
          width: 50px;
          height: 50px;
          background: chartreuse;
          z-index: 1000;
          border: 2px solid darkgreen;
       }
<div id="elm"></div>

In this code I add an img in .sec class but the image not working, how to fix this?

Note: The image path is valid. It's working for other cases, I mean when I add the same img in HTML, it works.

mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

0

You need use relative path for your image instead of absolute path.

You can copy image to same folder with html file and use

LPimg.src = "hacker8.jpeg";

Or put to images folder same level with html file and use

LPimg.src = "images/hacker8.jpeg";
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62