Created
September 8, 2016 09:37
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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