Chris Chris - 11 days ago 7
HTML Question

Inserting text after a certain image using javascript

In one function I have a loop that creates 10 images using the createElement();. In the other function I have another loop that contains info that I need to add text after each picture but my code adds it at the end of all 10 pictures I need them to be after every corresponding picture.
This is the function that displays the text:

function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");

span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
display.appendChild(span1);
}
}


I cant individually set the id of each image because i created them in js. Thanks for the help in advance and no jquery please

for (var x = 0; x<json.length;x++){
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
display.appendChild(image);

var a = document.getElementById("artist");
var y = document.getElementById("year");
var artist = document.getElementById("artist").selectedIndex;//index of value of the switch statement
var year = document.getElementById("year").selectedIndex;//index of value of the switch statement
var realYear = y[year].text;//Value of the selected text
var realArtist = a[artist].text;//Value of the selected text
var display = document.getElementById("Results");
}


This is my second loop. I want displayalbum to appear after every picture. I cannot combine them because of other complications in the code

Answer

The loop where you are creating images, give a unique id to image like image.id = "picture" + x;

Then change displayAlbum() function to use corresponding image to place the span tag.

function displayAlbum(json){
  for (var x = 0; x<json.length;x++){
    var span1 = document.createElement("span");
    span1.innerText = json[x].album;
    console.log(json[x].album);

    var display = document.getElementById("results");
    var img = document.getElementById("picture" + x); // use unique id of img to access it
    if(img.nextSibling) { // if img is not the last node in 'results'
      display.insertBefore(span1, img.nextSibling);
    } else { // if img is the last node in 'results'
      display.appendChild(span1);
    }
  }
}