I have the following JavaScript code that is triggered once DOM is loaded:
const add_note = () => {
// Creates a new note and its props
const new_note = document.createElement("div");
const new_input = document.createElement("input");
const new_form = document.createElement("form");
const new_ol = document.createElement("ol");
const new_button = document.createElement("button");
//Populates the new note with inputs and checkboxes
for (let i = 0; i < 5; i ) {
let new_li = document.createElement("li");
let new_checkbox = document.createElement("input");
new_checkbox.setAttribute("type", "checkbox");
let new_li_input = document.createElement("input");
new_li_input.classList.add("li_input");
new_ol.appendChild(new_li);
new_li.appendChild(new_checkbox);
new_li.appendChild(new_li_input);
}
//New note's settings
new_note.setAttribute("id", "note");
new_note.classList.add("note");
new_note.appendChild(new_input);
new_input.classList.add("note_input");
new_input.setAttribute("placeholder", "Note's title");
new_note.appendChild(new_form);
new_form.appendChild(new_ol);
new_ol.setAttribute("id", "ol_id");
new_note.appendChild(new_button);
new_button.classList.add("more_items");
new_button.setAttribute("id", "more_items");
//Inserts the new note and button
const note_block = document.getElementById("notes");
note_block.appendChild(new_note);
const button = document.getElementById("more_items");
button.addEventListener("click", add_more_items);
button.innerHTML = " ";
};
However, once the notes are created, only the first note button inherits its functions as seen on the following image: Code loaded
I've tried about everything I can but couldn't figure it out. Anyway thanks in advance.
CodePudding user response:
IDs are unique in html, you can't have multiple elements with the same id
Either remove these lines, make them into classes, or somehow distinguish them:
new_note.setAttribute("id", "note");
...
new_ol.setAttribute("id", "ol_id");
...
new_button.setAttribute("id", "more_items");
And just refer to the button with the variable:
const note_block = document.getElementById("notes");
note_block.appendChild(new_note);
new_button.addEventListener("click", add_more_items);
new_button.innerHTML = " ";
You could actually even move these last two lines up to the rest of your code before appending the note block.