Dimitri Vanhecke
Dimitri Vanhecke

Reputation: 1

setting up img in a nested div setting

I have a nested DIV structure (part of a modal) looking like this:

<div id="myModal" class="modal">
  <div id="myModalContent" class="modal-content">
    <div class="mySlides" id="mySlides1">
      <div class="numbertext1">1 / 5</div>
      <img src="clearmedium.JPG" id="S0Large" style="width:100%">
    </div>
  </div>
</div>

I would like to dynamically add slides (images) using JavaScript only (no jQuery), but don't seem to be able to figure out how.

I understand I have to create an 'img' element, give it a bunch of attributes (src, id, ...) and what I call a 'text' element and append both to the parent (modalDIVContent). Then I should append this DIV to the document. Doesn't seem to work though. The result is that there appears no image in the DIV. There is no other error.

I have:

var modalDIVContent = document.getElementById("myModalContent");
var innerDiv = document.createElement('div');
innerDiv.className = 'mySlides';
innerDiv.setAttribute("id", "mySlides" );        
modalDIVContent.appendChild(innerDiv);

var innertxt = document.createElement('div');
innertxt.setAttribute('class', 'numbertext');
innerDiv.appendChild(innertxt);
modalDIVContent.appendChild(innerDiv);

var innerImg = document.createElement('img');
innerImg.setAttribute('src', 'clearmedium.JPG');
innerImg.setAttribute('id', 'S1Large');
innerImg.style.width = "100%"
innerDiv.appendChild(innerImg);

Upvotes: 0

Views: 91

Answers (1)

Nicholas
Nicholas

Reputation: 3784

The code works, the problem is in the way you call the image. The path to your project images is not right and that's why you cant see any images.

Please check this example(your code) but the images come from some external links.

var modalDIVContent = document.getElementById("myModalContent");
var innerDiv = document.createElement('div');
innerDiv.className = 'mySlides';
innerDiv.setAttribute("id", "mySlides" );        
modalDIVContent.appendChild(innerDiv);

var innertxt = document.createElement('div');
innertxt.setAttribute('class', 'numbertext');
innerDiv.appendChild(innertxt);
modalDIVContent.appendChild(innerDiv);

var innerImg = document.createElement('img');
innerImg.setAttribute('src', 'https://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg');
innerImg.setAttribute('id', 'S1Large');
innerImg.style.width = "100%"
innerDiv.appendChild(innerImg);
<div id="myModal" class="modal">
  <div id="myModalContent" class="modal-content">
    <div class="mySlides" id="mySlides1">
      <div class="numbertext1">1 / 5</div>
      <img src="http://www.clickgratis.com.br/fotos-imagens/foto/aHR0cDovL2UwMy1lbG11bmRvLnVlY2RuLmVzL2Fzc2V0cy9tdWx0aW1lZGlhL2ltYWdlbmVzLzIwMTUvMTEvMTMvMTQ0NzQzMDAxNTczMDIuanBn.jpg" id="S0Large" style="width:100%">
    </div>
  </div>
</div>

Upvotes: 0

Related Questions