alex alex - 5 months ago 8
Javascript Question

JavaScript - How to put multiple LI into 1 UL using DOM

I'm trying to put multiple

li
into 1
ul
using DOM but it doesn't work, i tried different ways still doesn't work.
I got this code so far

var list = [
{
id: 1,
title: "Dope",
img: "pic/dope.jpg",
link: "dope.html"
},
{
id: 2,
title: "The Do Over",
img: "pic/The_Do-Over.png",
link: "The_Do-Over.html"
},
{
id: 3,
title: "Deadpool",
img: "pic/Deadpool.jpg",
link: "Deadpool.html"
},
{
id: 4,
title: "Johnny English Reborn",
img: "pic/johnny_english_reborn.jpg",
link: "johnny_english_reborn.html"
}
];

var input = document.getElementById("input");

for (var i = 0; i <list.length; i++) {
var ul = document.createElement('ul');
var li = document.createElement('li');
var a = document.createElement("a");
var img = document.createElement("img");
var p = document.createElement('p');

p.title = list[i].title;
ul.appendChild(p);
img.src = list[i].img;
img.title = list[i].title;

a.href = list[i].link;
a.appendChild(img);

li.id = list[i].id;
li.appendChild(a);
ul.appendChild(li);
console.log(ul);
input.appendChild(ul);
};


<div id="input" >

</div>

Answer

Try doing this:

var list = [
    {
        id: 1,
        title: "Dope",
        img: "pic/dope.jpg",
        link: "dope.html"
    },
    {
        id: 2,
        title: "The Do Over",
        img: "pic/The_Do-Over.png",
        link: "The_Do-Over.html"
    },
    {
        id: 3,
        title: "Deadpool",
        img: "pic/Deadpool.jpg",
        link: "Deadpool.html"
    },
    {
        id: 4,
        title: "Johnny English Reborn",
        img: "pic/johnny_english_reborn.jpg",
        link: "johnny_english_reborn.html"
    }
];

var input = document.getElementById("input");

function createList() {

    var ul = document.createElement('ul');

    for (var i = 0; i <list.length; i++) {


        //create li
        var li = document.createElement('li');
        li.id = list[i].id;

        //create paragraph
        var p = document.createElement('p');
        p.title = list[i].title;
        li.appendChild(p);

        //create image
        var img = document.createElement("img");
        img.src = list[i].img;
        img.title = list[i].title;

        //create href
        var a = document.createElement("a");
        a.href = list[i].link;    
        a.appendChild(img);
        li.appendChild(a);

        //append this li to the ul
        ul.appendChild(li);

    }

    //outside the loop, append once the ul to the wrapper
    input.appendChild(ul);


};

createList();