Skip to content

Instantly share code, notes, and snippets.

@ahoffmeyer
Created September 8, 2016 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoffmeyer/c1a61e0be34338ed8a35650ef4ba3505 to your computer and use it in GitHub Desktop.
Save ahoffmeyer/c1a61e0be34338ed8a35650ef4ba3505 to your computer and use it in GitHub Desktop.
Render DOM elements by array values and removing specific elements by clicking on them
/*
Function creates a list of DOM elements according to the given array.
Clicking on an item will remove it from DOM as well as from array as it uses splice.
*/
(function(){
"use strict";
let array = ["foo", "bar", "bax"];
let clickMe = () => {
// iterate through array
// forEach has no return ar mutation on array
array.forEach((val, index) => {
// create new DOM elements on each iteration
let domList = document.createElement("div"),
domListContent = val;
// fill the dom element with text
domList.innerText = domListContent;
// add eventlistener on new DOM element
domList.addEventListener("click", () => {
// remove clicked item from array
array.splice(index,1);
// update DOM
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
return clickMe();
});
// append elements to BODY
document.body.appendChild(domList);
});
};
clickMe();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment