Skip to content

Instantly share code, notes, and snippets.

@HTMLToronto
Created January 10, 2014 02:14
Show Gist options
  • Save HTMLToronto/8345873 to your computer and use it in GitHub Desktop.
Save HTMLToronto/8345873 to your computer and use it in GitHub Desktop.
// Generit list of fruits. Using this method of “for”, an object would not work
var fruits = ['mango', 'grapes', 'lemon', 'grapefruit', 'melon'];
(function () {
"use strict";
// Setup the i variable within the current function
var i, li, body,
// Set the fruit list dom element via ID since class would imply more than 1
fruitList = document.getElementById('fruits');
// A class selector could be used via querySelector or querySelectorAll
// but that method is not very backwards compatible
// If the fruits DOM element doesn’t exist, create it within the body
if (!fruitList) {
// Select the body tag
body = document.getElementsByTagName('body')[0];
// Create a list element
fruitList = document.createElement('ul');
// Append the list to the body as the last element
body.appendChild(fruitList);
}
// Loop through the available fruits
// Using the i = i + 1 method instead of i++ due to JSLint’s recommendation
for (i = 0; i < fruits.length; i = i + 1) {
// Create new list element
li = document.createElement('li');
// Set the content of the element
li.innerHTML = fruits[i];
// Append it to the list DOM element
fruitList.appendChild(li);
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment