Create a <Ul> and Fill It Based on a Passed Array

Create a ul and fill it based on a passed array

First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:

var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
];

function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');

for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');

// Set its contents:
item.appendChild(document.createTextNode(array[i]));

// Add it to the list:
list.appendChild(item);
}

// Finally, return the constructed list:
return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));

Here's a demo. You might also want to note that set0 and set1 are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:

var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};

And access them like so:

makeUL(options.set0);

Javascript add li to ul using array

From what I can see, you're trying to insert elements into the document which is embeded via iFrame. But you can't do this that simple.
The thing is that when you call document.getElementById from the parent (not iframe) window, it tries to find an element within parent window. But iFrame is a separate window.

You can try following.

In every specific game html file:

<body>
<!-- SOME CONTENT HERE -->

<!-- RIGHT BEFORE `BODY` CLOSE -->
<script>
// This will run your code once document is loaded.
window.onload = function () {
// run the createName function
createName();
// run the createList function
createList();
//play game
playGame(target);
};
</script>
</body>

In learningGames.js:

function populateSpellList() {  

// for loop should run through spelling list array and create list items in "listSpelling"
var i;
for (i = 0; i < spellingList.length; i++ ) {

var newLI = document.createElement("li"), // create a new li
displaySpellList = document.getElementById("listSpelling"), // cache the unordered list
newContent = document.createTextNode(spellingList[i]); // grab the spelling list item

// add the spelling list item to the li
newLI.appendChild(newContent);

displaySpellList.appendChild(newLI);
}
}

function gameWindow(target) {
// set the iframe html to the target html
document.getElementById('game_frame').src = target;
}

Hope it is exactly what you need.

Creating a UL from nested array

You can do it with 2 for loops(nested for loops). Implement the same kind of for loop if the directory[i] has a files array.

var directory = [    {type: "file", name: "file1.txt"},    {type: "file", name: "file2.txt"},    {type: "directory", name: "HTML Files", files: [{type: "file", name: "file1.html"},{type: "file", name: "file2.html"}]},    {type: "file", name: "file3.txt"},    {type: "directory", name: "JavaScript Files", files: [{type: "file", name: "file1.js"},{type: "file", name: "file2.js"},{type: "file", name: "file3.js"}]}];
window.onload = function(){ var ol = "<ol>"; for(var i = 0; i < directory.length; i++){ ol += "<li>" + directory[i].name; if(directory[i].files) { ol += "<ol>"; for(var j = 0; j < directory[i].files.length; j++) { ol += "<li>" + directory[i].files[j].name + "</li>"; } ol += "</ol>"; } ol += "</li>"; } ol += "</ol>";
var myContainer = document.querySelector("#olContainer").innerHTML = ol;};
<div id="olContainer"></div>

Displaying an array in a UL using javascript

You're pretty much there. You had a couple of issues:

  • You already have specified a ul element within your HTML. You don't need to re-create it again by doing document.createElement('ul'), just select the ul instead
  • You had your ul element's id as the number 1. When you tried to select the ul by doing document.getElementById(1)`, that will not work. You need to pass in the string of the id. I rename it to 'one' to fix it.
  • In your for(...) loop, you had a semi colon (;) after for(...);. That will not work. I removed the semi colon for you.
  • You last line of code ul.appendChild(li) is the only thing you need to do after you set your innerHTML. You already have the ul in the dom, so just append your new elements to that.

Example:

function load() {
const favLanguages = ["html", "css", "javascript", "go", "ruby"];

// Get a refrerence to the UL
const ul = document.getElementById('one');

for (i = 0; i <= favLanguages.length; i++) {
const li = document.createElement("li"); // create li element.

li.innerHTML = favLanguages[i]; // assigning text to li using array value.

ul.appendChild(li); // append li to ul.
}
}

load();
<h1>My favourite languages:</h1>

<ul id="one"></ul>

Generate dinamically a ul li listing from a input array in jQuery

I reworked my project so that it is as close as possible to what you need.
This is not jQuery but I hope this helps you!

JS / HTML / CSS

var arrayOfFiles = [
"/first_folder/app_01.dat",
"/first_folder/app_02.dat",
"/first_folder/second_folder/ret_01.dat",
"/first_folder/second_folder/ret_02.dat",
"/first_folder/second_folder/third_folder",
"/other_first_folder/other_app_01.dat",
"/other_first_folder/other_app_02.dat",
"/other_first_folder/other_sec_folder/other_app_03.dat",
"/other_first_folder/other_sec_folder/other_app_04.dat",
"/new_folder/new_other_folder/last_folder",
];

var wrap = document.getElementById("myTreeSelector");

var lines = "----";
var res = {};
function makeObj(obj) {
var splme = obj.split('/').slice(1);
var f = res;
for (i = 0; i < splme.length; i++) {
obName = { name: splme[i] };
f = f[splme[i]] = f[splme[i]] || obName;
}
}
arrayOfFiles.map(makeObj);

var tmp = [];
function prsObj(x, y) {
for (var k in x) {
if (typeof x[k] === 'object' && x[k] !== null) {
prsObj(x[k], y);
}
else if (x.hasOwnProperty(k)) {
y(x[k]);
}
tmp.push(lines);
}
};
prsObj(res, function (ftmp) { tmp.push(ftmp); });

var redy = [];
for (var i = 0; i < tmp.length - 1; i++) {
if (tmp[i] !== lines) {
redy.push(tmp[i]);
}
else if (tmp[i] === lines && tmp[i + 1] === lines) {
redy.push("file");
i++;
}
else if (tmp[i] === lines && tmp[i + 1] !== lines) {
redy.push("folder");
} else { }
}
redy.pop();

var text = '';
var x = 0;
var y = 0;
for (var i = 0; i < redy.length; i++) {
if (y === 1) {
var text = document.createTextNode(redy[i]);
addThis(0);
x = 0;
y = 0;
}
else if (redy[i + 1] === "file" && redy[i + 2] === "file") {
if (redy[i].indexOf(".") > -1) {
var text = document.createTextNode(redy[i]);
addThis(1);
i = i + 2;
x = 0;
y = 1;
} else {
var text = document.createTextNode(redy[i]);
addThis(2);
i = i + 2;
x = 0;
y = 1;
}
}
else if (redy[i + 1] === "folder" && i === 0) {
var text = document.createTextNode(redy[i]);
addThis(0);
x++;
y = 0;
}
else if (redy[i + 1] === "folder" && x >= 1 || redy[i + 1] === "folder") {
var text = document.createTextNode(redy[i]);
addThis(2);
x++;
y = 0;
}
else if (redy[i + 1] === "file") {
if (redy[i] === '') { continue; }
else if (redy[i].indexOf(".") > -1) {
var text = document.createTextNode(redy[i]);
addThis(1);
y = 0;
} else {
var text = document.createTextNode(redy[i]);
addThis(2);
y = 0;
}
}
else { }
}

function addThis(x) {
if (x === 0) {
var li = document.createElement("li");

var span = document.createElement("span");
span.setAttribute("class", "caret folder-selector");

var iel = document.createElement("i");
iel.setAttribute("class", "fa fa-folder");

var ul = document.createElement("ul");
ul.setAttribute("class", "nested");

span.appendChild(iel);
span.appendChild(text);
li.appendChild(span);
wrap.appendChild(li);
li.appendChild(ul);
}

if (x === 1) {
var get = wrap.getElementsByClassName("nested");
var ul = get[get.length - 1];

var iel = document.createElement("i");
iel.setAttribute("class", "fa fa-file");

var li = document.createElement("li");
li.setAttribute("class", "file");

ul.appendChild(li);
li.appendChild(iel);
li.appendChild(text);
}

if (x === 2) {
var get = wrap.getElementsByClassName("nested");
var ul = get[get.length - 1];

var li = document.createElement("li");

var span = document.createElement("span");
span.setAttribute("class", "caret folder-selector");

var iel = document.createElement("i");
iel.setAttribute("class", "fa fa-folder");

ul.appendChild(li);
li.appendChild(span);
span.appendChild(iel);
span.appendChild(text);

var get = wrap.querySelectorAll("li")
var li = get[get.length - 1];
var ul = document.createElement("ul");
ul.setAttribute("class", "nested");

li.appendChild(ul);
}
}
ul {
list-style-type: none;
}

i {
margin-right: 5px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />

<ul id="myTreeSelector">
</ul>

How to populate multiple JavaScript arrays of objects to HTMLDOM

If you change the order of for loops execution and append each string to the previous it works!

const allData = [{
date: '2nd',
venue: 'venue1',
location: 'location1',

},

{
date: '3rd',
venue: 'venue2',
location: 'location2',

},

{
date: '4th',
venue: 'venue3',
location: 'location3',

},
];

const list = document.querySelector('.target')
let innerHTML = '';
allData.forEach(data => {
innerHTML += `
<li>
<h5 class = "shows__date">DATE</h5>
<h4 class = "shows__calander">${data.date}</h4>
<h5 class = "shows__venue-title">VENUE</h5>
<h4 class = "shows__venue">${data.venue}</h4>
<h5 class = "shows__location-title">LOCATION</h5>
<h4 class = "shows__location">${data.location}</h4>
<Button Class = "shows__btn">BUY TICKETS</Button>
</li>
`;
});

list.innerHTML = innerHTML;
<ul class="target">
</ul>


Related Topics



Leave a reply



Submit