How to show element created in javascript as child?

I can successfully add div to my “.list-group” div and localstorage, they work dynamically. But these elements do not appear to be offspring of its container. If you try it in your own browser, you will see that it returns a null value. Why don’t my list items appear as kids? And how can I make it appear Child. Thank’s adavance for your answers. Codepen: https://codepen.io/BerkayAkgurgen/pen/xxEmQLo

const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
let alert = document.getElementById("alertID");
eventListeners();
console.log(todoList.firstElementChild);

//Event Listeners

function eventListeners() {
    secondCardBody.addEventListener("click", deleteTodo);
    form.addEventListener("submit", addTodo);
    document.addEventListener("DOMContentLoaded", loadAllTodosToUI);
    filter.addEventListener("keyup", filterTodos);
    clearButton.addEventListener("click",clearAllTodos);
}

// Todo Ekleme

function addTodo(e) {
    const newTodo = todoInput.value.trim();
    if (newTodo === "") {
        showAlert("danger", "Lütfen bir todo giriniz");
    } else {
        showAlert("success", "Giriş Başarılı");
        addTodoToUI(newTodo);
        addTodoToStorage(newTodo);
    }
    e.preventDefault();
}


function addTodoToUI(newTodo) {
    const listItem = document.createElement("li");
    const link = document.createElement("a");
    link.href = "#";
    link.className = "delete-item";
    link.innerHTML = " <i class = 'fa fa-remove'></i>";
    listItem.className = "list-group-item d-flex justify-content-between";
    listItem.appendChild(document.createTextNode(newTodo));
    listItem.appendChild(link);
    todoList.appendChild(listItem);
    todoInput.value = "";
}

// Alert

function showAlert(type, message) {
    let = alert;
    if (alert == null) {
        alert = document.createElement("div");
        alert.className = `alert alert-${type}`;
        alert.id = "alertID";
        alert.textContent = message;
        firstCardBody.appendChild(alert);
        alert.style.marginTop = "1rem";
    } else {
        alert.className = `alert alert-${type}`;
        alert.textContent = message;
        document.getElementById("alertID").style.display = 'block';
    }
    setTimeout (function myFunction2() {
        document.getElementById("alertID").style.display = 'none'; 
    }, 1000)
};

// Todo Storage Ekleme

function addTodoToStorage(newTodo) {
    let todos = getTodosFromStorage();

    todos.push(newTodo);

    localStorage.setItem("todos", JSON.stringify(todos));
}

function getTodosFromStorage() { // Storage'den Todoları Almak
    let todos;
    if (localStorage.getItem("todos") === null) {
        todos = [];
    } else {
        todos = JSON.parse(localStorage.getItem("todos"));
    }
    return todos;
}

// Sayfa Yüklendiğinde Storage Yükleme

function loadAllTodosToUI() {
    let todos = getTodosFromStorage();

    todos.forEach(function (todo) {
        addTodoToUI(todo);
    })
}

// Todo Silme

function deleteTodo(e) {
    if (e.target.className === "fa fa-remove") {
        e.target.parentElement.parentElement.remove();
    }
}

// Todo Filtreleme

function filterTodos(e) {
    const filterValue = e.target.value.toLowerCase();
    const listItems = document.querySelectorAll(".list-group-item");

    listItems.forEach(function (listItem) {
        const text = listItem.textContent.toLowerCase();
        if (text.indexOf(filterValue) === -1) {
            // Bulamadı
            listItem.setAttribute("style", "display : none !important");
        } else {
            listItem.setAttribute("style", "display : block");
        }
    });
}

// Tüm Todoları Silme

function clearAllTodos(e) {
    if (confirm("Tümünü Silmek istediğinize Emin Misiniz?")) {
        // Arayüzden Todoları Temizleme 
        // todoList.innerHTML = ""; // Yavaş Yöntem
    }
}
console.log(todoList.firstElementChild);

Are you talking about this log statement?

console.log(todoList.firstElementChild);

Because it just runs (synchronously) at the start before any items have been added and before the localStorage has loaded.

If you want to see it log the items you can add it as the last call inside the functions that perform updates.

Example:

function loadAllTodosToUI() {
  let todos = getTodosFromStorage();

  todos.forEach(function (todo) {
    addTodoToUI(todo);
  });
  
  console.log("loadAllTodosToUI", todoList.firstElementChild);
}

Or if you had created a render function that was responsible for updating the UI based on some data structure (like an array of objects) it would also be a good place to log the DOM elements.

What I mean is, for example, the addTodo function would add a todo object to an array but not do any DOM manipulation. The DOM manipulation would happen inside a separate (render) function that gets called and reads the data structure to update the UI.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.