DEV Community

Cover image for 👨‍💻 Daily Code 40 | Rendering 🟥 HTML with 🟨 JS
Gregor Schafroth
Gregor Schafroth

Posted on

👨‍💻 Daily Code 40 | Rendering 🟥 HTML with 🟨 JS

🙋‍♂️ Hi everyone!

Today I continued following the free SuperSimpleDev course and learned how to generate HTML with JS. This is so cool, now I suddenly realize how many websites are made that have complicated repeating elements!

My Code

The actual project I made in that course is just a todo list. Nothing special. But rendering the HTML is just cool 🙂 - Oh yea also now we separated the JavaScript and saved it in a separate file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List</title>
</head>

<body>
    <p>Todo List</p>
    <input placeholder="Todo name" class="js-name-input">
    <button onclick="addTodo();">Add</button>
    <div class="js-todo-list"></div>
    <script src="scripts/11-todo.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode
const todoList = ['make dinner', 'wash dishes'];

renderTodoList();

function renderTodoList() {
    let todoListHTML = '';

    for (let i = 0; i < todoList.length; i++) {
        const todo = todoList[i];
        const html = `<p>${todo}</p>`; // 'generating the HTML'
        todoListHTML += html;
    }
    console.log(todoListHTML);

    document.querySelector('.js-todo-list').innerHTML = todoListHTML;
}

function addTodo() {
    const inputElement = document.querySelector('.js-name-input');
    const name = inputElement.value;

    todoList.push(name);
    console.log(todoList);

    inputElement.value = ''

    renderTodoList();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)