July 7, 2020
How to Remove Empty Elements from Array in Javascript
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Remove</button> <h1>Length</h1> <ul></ul> </div> <script src="script.js"></script> </body> </html> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; } li { font-weight: bold; font-size: 20px; list-style: none; margin-left: -40px; } |
Javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let users = ['Marks', 'James', 'Jane', null, , 'Peter', 'Ronald']; function addUsers(){ let template = users.map(user => `<li>${user}</li>`).join('\n'); document.querySelector('ul').innerHTML = template; document.querySelector('h1').innerText = users.length; } addUsers(); let btnRemove = document.querySelector('button'); btnRemove.addEventListener('click', () => { users = users.filter(user => user != null); addUsers(); }); |