I am trying to create a single page todo app with plain javascript. There is a button on the page that takes the text value from textbox and creates a button with that input value. What I am trying to do is passing a button's text value, which is created by user dynamically, to another element, a h2 element for example. Here are screenshots to explain what I mean;
Type a list name and click Create List button;
A button is created with the input text value. Now when you click the List 1 button, text value of that button, "List 1", should pass to h2 element on the right;
Here is my code so far;
<div class="container" id="table-and-list-names">
<div class="row">
<div class="col-3">
<ul class="nav flex-column" id="list-names">
<!--Names of Lists created by user will be here-->
</ul>
</div>
<!--TABLE-->
<div class="col-9">
<h2 id="current-list-name">Select Todo List</h2>
//...
Create button;
export function createButton(listName) {
const listOfLists = document.querySelector('#list-names');
const newList = document.createElement('li');
const newListButton = document.createElement('button');
newListButton.classList.add("btn", "btn-sm", "btn-outline-primary", "created-list");
newListButton.innerText = listName;
newList.appendChild(newListButton);
listOfLists.appendChild(newList);
}
I tried to pass the text value with this code but didn't work;
const currListName = document.querySelector('#current-list-name');
var buttons = document.getElementsByClassName('.created-list');
var buttonCount = buttons.length;
for (var i = 0; i <= length; ++i)
buttons[i].onClick = function(e) {
currListName.textContent = buttons[i].textContent;
};
Nothing happens when I click the button, no errors on the browser console. I only get an error when I refresh the page and it says "Uncaught TypeError: can't access property "onClick", buttons[i] is undefined". I think that is because there is no button when I refresh the page. Any suggestions?
So how is this newListButton supposed to know what is has to do? You have to tell it to him, by attaching an eventListener or creating an onlick handler.