Я тоже сделал немного re-factoring
~ aka playing
, что, возможно, могло бы быть полезным / интересным?!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Trees in the Forest</title>
<style>
body, body *{ box-sizing:border-box;font-family:monospace }
#forest{ width:100%; height:50vh;}
.tree{
width:50px;
height:80px;
margin:0.25rem;
background:url(https://png.pngtree.com/element_our/sm/20180527/sm_5b0b21833edb1.png);
background-size:contain;
background-repeat:no-repeat;
background-position:bottom;
background-color:rgba(0,200,0,0.1)
}
ol{ width:100%; margin:1rem auto }
ol > li{display:inline-block;text-align:center}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
const domTarget=function(n){
return document.getElementById( n );
};
/* utility to generate new DOM elements with attributes and value */
const create=function(t,a,p){
let el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
let _arr=['innerHTML','innerText','html','text'];
for( let x in a ) if( a.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, a[ x ] );
if( a.hasOwnProperty('innerHTML') || a.hasOwnProperty('html') ) el.innerHTML=a.innerHTML || a.html;
if( a.hasOwnProperty('innerText') || a.hasOwnProperty('text') ) el.innerText=a.innerText || a.text;
if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
return el;
};
/* wrapper for rebuilding the OL contents */
const createforest=function(a,p){
p.innerHTML=''; // clear previous content
a.sort( ( x, y )=>{ return x > y ? 1 : -1 } ) // sort the array alphabetically
a.forEach( tree => { create( 'li',{ text:tree, 'class':'tree', 'data-tree':tree }, p ); } ); // add each tree
};
/* The initial collection of trees */
let trees=[ 'spruce', 'pine', 'cedar' ];
/* Existing DOM elements */
let forest=domTarget('forest');
let bttn=document.querySelector('form > input[ type="button" ]');
let ol=create( 'ol', {}, forest );
/* create the initial display of trees */
createforest( trees, ol );
/* Listen for button clicks - add new tree to the array and rebuild display */
bttn.addEventListener( 'click', function(e){
let input=this.previousElementSibling;
if( input.value!='' ){
if( trees.length >= 3 ){
/* add to the array */
trees.push( input.value );
/* rebuild the display */
createforest( trees, ol );
/* clear the input field */
input.value='';
input.focus();
}
return true;
}
alert( 'Please enter a tree name' );
});
/* listenen for clicks on parent container */
ol.addEventListener('click',(e)=>{
if( e.target!=e.currentTarget ){
/* remove tree from array and display */
let tree=e.target.dataset.tree;
trees.splice( trees.indexOf( tree ), 1 );
e.target.parentNode.removeChild( e.target );
}
});
})
</script>
</head>
<body>
<div id='forest'></div>
<form>
<input type='text' />
<input type='button' value='Add Tree' />
</form>
</body>
</html>