How put button into variable when it appears after page onload - javascript

How can I get the button add__deal__btn after it appears? When the page loads add__deal__btn doesn't exist, but after I add the task__card to the div it appears. How can I manipulate the button after it appears?
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];
addBtn.onclick = function() {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerHTML = addTitle.value
task.appendChild(taskTitle)
addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerHTML = "Add deal";
task.appendChild(addDealBtn);
tasks.append(task);
}
//THIS CODE DOESN'T WORK
addDeal = document.querySelectorAll('.add__deal__btn');
for(let i = 0;i<addDeal.length;i++){
addDeal[i].onclick= function(){
alert();
}
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>
Thank you

Add the onclick event when you create the button.
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];
addBtn.onclick = function() {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerHTML = addTitle.value
task.appendChild(taskTitle)
addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerHTML = "Add deal";
// Add onclick event here
addDealBtn.onclick = function() {
alert('Button clicked!');
};
task.appendChild(addDealBtn);
tasks.append(task);
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>

The line addDeal = document.querySelectorAll('.add__deal__btn'); only runs once (when the script loads). At that time, no <button> elements with class add__deal__btn exist in the DOM.
To achieve what you want simply add the event listener to each newly generated button. Like this:
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
addBtn.onclick = function () {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerText = addTitle.value;
task.appendChild(taskTitle);
let addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerText = "Add deal";
task.appendChild(addDealBtn);
tasks.append(task);
addDealBtn.onclick = function() {
alert('Hey it works!');
};
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>
Tip: You don't need to create an array to store each new button you create anymore.

Related

How to create a new list element i javascript without creating new ul-elements for each new item

I'm trying to create a tasklist in javascript. I want the user to be able to add new list items as tasks, but I cannot figure out how to do next...
So my problem is the following:
for each new input the user gives, instead of adding on li-element to the ul-element, new ul-elements keep creating containing only one li-element. How do I do to add li-elements to the same ul-element, without creating new ul-elements for each new task/input created?
This is html and javascript code:
<html>
<body>
<div id="createNewTaskContainer">
<form id="taskForm">
<input id="taskInput" type="text" />
<button type="submit" id="createTaskButton">Add</button>
</form>
</div>
<div id="listOfTasksContainer"></div>
</body>
</html>
let toDoList = [];
window.onload = function () {
let form = document.getElementById("taskForm");
form.addEventListener("submit", addTask); }
function insertTasksInHtml() {
let liElement = document.createElement("li");
let ulElement = document.createElement("ul");
ulElement.appendChild(liElement);
document.getElementById("listOfTasksContainer").innerHTML = "";
document.getElementById("listOfTasksContainer").appendChild(ulElement);
console.log(ulElement);
for (let i = 0; i < toDoList.length; i++) {
liElement.innerText = toDoList[i];
}
}
function addTask(e) {
e.preventDefault();
let taskInput = document.getElementById("taskInput").value;
if (taskInput === "") {
alert("Please insert a task before you submit");
} else {
toDoList.push(taskInput);
insertTasksInHtml();
}
}
let toDoList = [];
window.onload = function () {
let ulElement;
let node;
let textnode;
let form = document.getElementById("taskForm");
form.addEventListener("submit", addTask); }
function insertTasksInHtml(newTask) {
ulElement = document.getElementById("list");
node = document.createElement("li");
textnode = document.createTextNode(newTask);
node.appendChild(textnode);
ulElement.appendChild(node);
}
function addTask(e) {
e.preventDefault();
let taskInput = document.getElementById("taskInput").value;
if (taskInput === "") {
alert("Please insert a task before you submit");
} else {
toDoList.push(taskInput);
insertTasksInHtml(taskInput);
}
}
<html>
<body>
<div id="createNewTaskContainer">
<form id="taskForm">
<input id="taskInput" type="text" />
<button type="submit" id="createTaskButton">Add</button>
</form>
</div>
<div id="listOfTasksContainer">
<ul id="list">
</ul>
</div>
</body>
</html>
Create liElement inside the loop and append to Ul.
function insertTasksInHtml() {
let ulElement = document.createElement("ul");
document.getElementById("listOfTasksContainer").innerHTML = "UL";
document.getElementById("listOfTasksContainer").appendChild(ulElement);
//console.log(ulElement);
for (let i = 0; i < 10; i++) {
let liElement = document.createElement("li");
liElement.innerText = 'LI ' + i;
ulElement.appendChild(liElement);
}
}
insertTasksInHtml();
<div id="listOfTasksContainer">
</div>

removing dynamically generated element using addeventlistener

i´m trying to add an eventlistener to a dynamically generated element. The listener is supposed to be for the button of the generated div. Every button has a unique id, based on the value entered in the input field.
Everything is working fine, but the eventlistener doesn´t.
Here is the code:
function updateList() {
let listItem = new Object();
listItem.name = document.getElementById('userListItem').value;
if (listItem.name.length >= 1) {
let timeWhenAdded = new Date();
listItem.timeStamp = `${timeWhenAdded.getDate()}.${timeWhenAdded.getMonth()+1}.${timeWhenAdded.getFullYear()},
at ${timeWhenAdded.getHours()}:${timeWhenAdded.getMinutes()} Uhr`;
let newDiv = document.createElement('div');
newDiv.className = 'Item';
newDiv.id = `${listItem.name}Item`;
let itemHeading = document.createElement('h2');
let itemDescription = document.createElement('p');
let deleteButton = document.createElement('button');
deleteButton.id = `${listItem.name}RemoveItemButton`;
deleteButton.className = `DeleteButton`;
newDiv.append(itemHeading, itemDescription, deleteButton);
let itemContent = document.createTextNode(listItem.name);
itemHeading.appendChild(itemContent);
let itemtime = document.createTextNode(`Added on: ${listItem.timeStamp}`)
itemDescription.appendChild(itemtime);
let itemRemover = document.createTextNode('remove');
deleteButton.appendChild(itemRemover);
let bucketListDiv = document.getElementById('bucket-list');
bucketListDiv.appendChild(newDiv);
document.getElementById('userListItem').value = "";
} else {
alert('Type an item in the input-field');
}
}
let ItemButton = document.getElementsByClassName('Item');
$(document).on('click', ItemButton, function() {
console.log('clicked button');
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>This is a list</h1>
<div class="userinput">
<input type="text" id="userListItem">
<button id="addButton" onclick="updateList()">add</button>
</div>
<div id="bucket-list"></div>
</body>
The RemoveItemButton is supposed to delete the whole generated div.
Target the element you click on instead.
function updateList() {
let listItem = new Object();
listItem.name = document.getElementById('userListItem').value;
if (listItem.name.length >= 1) {
let timeWhenAdded = new Date();
listItem.timeStamp = `${timeWhenAdded.getDate()}.${timeWhenAdded.getMonth()+1}.${timeWhenAdded.getFullYear()},
at ${timeWhenAdded.getHours()}:${timeWhenAdded.getMinutes()} Uhr`;
let newDiv = document.createElement('div');
newDiv.className = 'Item';
newDiv.id = `${listItem.name}Item`;
let itemHeading = document.createElement('h2');
let itemDescription = document.createElement('p');
let deleteButton = document.createElement('button');
deleteButton.id = `${listItem.name}RemoveItemButton`;
deleteButton.className = `DeleteButton`;
newDiv.append(itemHeading, itemDescription, deleteButton);
let itemContent = document.createTextNode(listItem.name);
itemHeading.appendChild(itemContent);
let itemtime = document.createTextNode(`Added on: ${listItem.timeStamp}`)
itemDescription.appendChild(itemtime);
let itemRemover = document.createTextNode('remove');
deleteButton.appendChild(itemRemover);
let bucketListDiv = document.getElementById('bucket-list');
bucketListDiv.appendChild(newDiv);
document.getElementById('userListItem').value = "";
} else {
alert('Type an item in the input-field');
}
}
$(document).on('click', '.DeleteButton', function() {
$(this).parent().remove();
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>This is a list</h1>
<div class="userinput">
<input type="text" id="userListItem">
<button id="addButton" onclick="updateList()">add</button>
</div>
<div id="bucket-list"></div>
</body>
Here is a working example using vanilla JavaScript:
document
.getElementById('bucket-list')
.addEventListener('click', ({ target }) => {
const btn = target.closest('.DeleteButton');
if (!btn) return;
btn.parentElement.remove();
});
function updateList() {
let listItem = {}; // just use an object literal!
listItem.name = document.getElementById('userListItem').value;
if (listItem.name.length >= 1) {
let timeWhenAdded = new Date();
listItem.timeStamp = `${timeWhenAdded.getDate()}.${timeWhenAdded.getMonth()+1}.${timeWhenAdded.getFullYear()},
at ${timeWhenAdded.getHours()}:${timeWhenAdded.getMinutes()} Uhr`;
let newDiv = document.createElement('div');
newDiv.className = 'Item';
newDiv.id = `${listItem.name}Item`;
let itemHeading = document.createElement('h2');
let itemDescription = document.createElement('p');
let deleteButton = document.createElement('button');
deleteButton.id = `${listItem.name}RemoveItemButton`;
deleteButton.className = `DeleteButton`;
newDiv.append(itemHeading, itemDescription, deleteButton);
let itemContent = document.createTextNode(listItem.name);
itemHeading.appendChild(itemContent);
let itemtime = document.createTextNode(`Added on: ${listItem.timeStamp}`)
itemDescription.appendChild(itemtime);
let itemRemover = document.createTextNode('remove');
deleteButton.appendChild(itemRemover);
let bucketListDiv = document.getElementById('bucket-list');
bucketListDiv.appendChild(newDiv);
document.getElementById('userListItem').value = "";
} else {
alert('Type an item in the input-field');
}
}
<body>
<h1>This is a list</h1>
<div class="userinput">
<input type="text" id="userListItem">
<button id="addButton" onclick="updateList()">add</button>
</div>
<div id="bucket-list"></div>
</body>

when I click on a element returns multiple times

this is my code(without css file):
var taskInput = document.getElementById("taskInput"),
taskList = document.getElementById("taskList");
taskList.addEventListener("click", changesLi);
function addTask() {
if (!taskInput.value) return alert("Please enter a task.");
var li = createLi(taskInput.value);
taskList.prepend(li);
taskInput.value = "";
}
function createLi(title) {
var li = document.createElement("li"),
span = document.createElement("span"),
div = document.createElement("div"),
remove = document.createElement("a"),
done = document.createElement("a"),
doneImg = document.createElement("img"),
removeImg = document.createElement("img");
span.textContent = title;
li.className = "task";
div.className = "links";
done.href = "#";
done.className = "done";
doneImg.alt = "done";
done.appendChild(doneImg);
remove.href = "#";
remove.className = "remove";
removeImg.alt = "remove";
remove.appendChild(removeImg);
li.appendChild(span);
li.appendChild(div);
div.appendChild(done);
div.appendChild(remove);
return li;
}
function changesLi(e) {
if (e.target.parentElement.classList.contains("remove")) {
e.target.parentElement.parentElement.parentElement.remove();
}
if (e.target.parentElement.classList.contains("done")) {
const tasks = document.querySelectorAll(".done");
tasks.forEach(task => {
task.addEventListener("click", function() {
console.log(e.target);
});
});
}
}
<form class="task-form" onsubmit="event.preventDefault();addTask()">
<input id="taskInput" placeholder="New task..." autocomplete="off" />
<input type="submit" value="Add Task" class="submit" />
</form>
<ul id="taskList"></ul>
When I click on a button that contains the done class, the e.target value returns to me as an array each time.
The first time I click, nothing returns. The second time, it returns the target once, the third time, the target twice, and so on...
No matter how much I searched, I didn't get any results. Where is my problem?
Whenever the user clicks on a done button, you're adding a click listener to all the done buttons. Adding a listener doesn't replace previous listeners, so each time they click it adds another listener. When they click again, it runs all the listeners that do the console.log(e.target), as well as the original listener that adds another listener to all the buttons.
You should just log what you want in the original listener, without adding any additional listeners.
var taskInput = document.getElementById("taskInput"),
taskList = document.getElementById("taskList");
taskList.addEventListener("click", changesLi);
function changesLi(e) {
if (e.target.parentElement.classList.contains("remove")) {
e.target.parentElement.parentElement.parentElement.remove();
} else if (e.target.parentElement.classList.contains("done")) {
console.log(e.target.parentElement.parentElement.parentElement.querySelector("span").textContent);
}
}
function addTask() {
if (!taskInput.value) return alert("Please enter a task.");
var li = createLi(taskInput.value);
taskList.prepend(li);
taskInput.value = "";
}
function createLi(title) {
var li = document.createElement("li"),
span = document.createElement("span"),
div = document.createElement("div"),
remove = document.createElement("a"),
done = document.createElement("a"),
doneImg = document.createElement("img"),
removeImg = document.createElement("img");
span.textContent = title;
li.className = "task";
div.className = "links";
done.href = "#";
done.className = "done";
doneImg.alt = "done";
done.appendChild(doneImg);
remove.href = "#";
remove.className = "remove";
removeImg.alt = "remove";
remove.appendChild(removeImg);
li.appendChild(span);
li.appendChild(div);
div.appendChild(done);
div.appendChild(remove);
return li;
}
<form class="task-form" onsubmit="event.preventDefault();addTask()">
<input id="taskInput" placeholder="New task..." autocomplete="off" />
<input type="submit" value="Add Task" class="submit" />
</form>
<ul id="taskList"></ul>
Each time you click a '.done' element, you are binding a new click event to each '.done' element:
if (e.target.parentElement.classList.contains("done")) {
const tasks = document.querySelectorAll(".done");
// for each '.done'
tasks.forEach(task => {
// add another callback for the click event
task.addEventListener("click", function() {
console.log(e.target);
});
});
}
And you don't need to do that. Just log the target:
if (e.target.parentElement.classList.contains("done")) {
console.log(e.target);
}

How to replace content of div element?

i want to add more than one element to my content it should be (h1,input and some buttons). So i wrote a function where i created h1 and input and now i try to add it to my div content and got an error (TypeError: Cannot read property 'appendChild' of undefined).
Here is my code:
let el = document.getElementById('add');
if (el) {
el.addEventListener('click', function () {
let rootDiv = document.getElementById('content');
rootDiv.innerHTML = addElement();
})
}
function addElement() {
let h = document.createElement("H1");
let t = document.createTextNode("Add task");
h.appendChild(t);
let input = document.createElement('INPUT');
document.rootDiv.appendChild(h);
document.rootDiv.appendChild(input);
}
let el = document.getElementById('add');
if (el) {
el.addEventListener('click', function() {
let rootDiv = document.getElementById('content');
addElement(rootDiv);
})
}
function addElement(rootDiv) {
let h = document.createElement("H1");
let t = document.createTextNode("Add task");
h.appendChild(t);
let input = document.createElement('INPUT');
rootDiv.appendChild(h);
rootDiv.appendChild(input);
}
<input type="button" id="add" value="Submit" />
<div id="content"></div>
If you need to continuosly replace content with new one instead of adding, you may add another function for clearing container before addElement.
Check this snippet:
let el = document.getElementById('add');
if (el) {
el.addEventListener('click', function() {
let rootDiv = document.getElementById('content');
clearDiv(rootDiv); // clear container before pasting new content
addElement(rootDiv);
})
}
function addElement(rootDiv) {
let h = document.createElement("H1");
let t = document.createTextNode("Add task");
h.appendChild(t);
let input = document.createElement('INPUT');
rootDiv.appendChild(h);
rootDiv.appendChild(input);
}
function clearDiv(div) { // function for clearing rootDiv
while (div.firstChild) {
div.removeChild(div.firstChild);
}
}
<input type="button" id="add" value="Submit" />
<div id="content"></div>
There is no such document.rootDiv on which you can implement appenChild().
You can append the child directly to the container element. You do not need to set the innerHTML. Simply call the function.
To clear the existing content, you can use
element.innerHTML = "" before appending the childs.
let el = document.getElementById('add');;
if (el) {
el.addEventListener('click', function () {
addElement();
});
}
function addElement() {
let rootDiv = document.getElementById('content')
rootDiv.innerHTML = "";
let h = document.createElement("H1");
let t = document.createTextNode("Add task");
h.appendChild(t);
let input = document.createElement('INPUT');
rootDiv.appendChild(h);
rootDiv.appendChild(input);
}
<button id="add">Add</button>
<div id="content"> <h1>Simple TODO application</h1> <button id="add">Add new task</button> <p>TODO is empty</p> <h1></h1>
</div>

Add and Remove button JavaScript [duplicate]

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 5 years ago.
I need make button to add and remove that adds and removes inputs.
Did I write normal script or adding button should be another?
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I made some modifications to Anu's answer, but this should do the trick.
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
var t = document.createTextNode("X");
btn.id = i;
btn.appendChild(t);
btn.onclick = function() {
$('#' + i).remove();
$('#' + i).remove();
i = i - 1;
};
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
const addButton = document.getElementById("add");
const hobbyWrapper = document.getElementById("hobby");
let i = 0
addButton.addEventListener("click", add);
function add (){
i = i + 1
const inputWrapper = document.createElement('div');
inputWrapper.id = `inputWrapper-${i}` ;
const input = document.createElement('input');
input.placeholder = "More hobbies";
inputWrapper.appendChild(input)
const removeButton = document.createElement('button');
removeButton.innerHTML = 'X';
removeButton.onclick = () => {
hobbyWrapper.removeChild(inputWrapper)
}
inputWrapper.appendChild(removeButton);
hobbyWrapper.appendChild(inputWrapper);
}
<div id="hobby">
<div id="inputWrapper">
<input placeHolder="Type your hobby">
<button>X</button>
</div>
</div>
<button id="add">Add hobby</button>
var div = document.getElementById('hobby');
function addHobby() {
var input = document.createElement('input'),
button = document.createElement('button');
input.placeholder = "More hobbies";
button.innerHTML = 'X';
// attach onlick event handler to remove button
button.onclick = removeHobby;
div.appendChild(input);
div.appendChild(button);
}
function removeHobby() {
// remove this button and its input
div.removeChild(this.previousElementSibling);
div.removeChild(this);
}
// attach onclick event handler to add button
document.getElementById('add').addEventListener('click', addHobby);
// attach onclick event handler to 1st remove button
document.getElementById('remove').addEventListener('click', removeHobby);
<div id="hobby">
<input placeHolder="Type your hobby" />
<button id="remove">X</button>
</div>
<button id="add">Add hobby</button>
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function(){
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
var button = document. createElement("button");
button. innerHTML = "X";
button.id=i;
button.onclick = function() {
div.removeChild(document.getElementById(button.id));
div.removeChild(button)
}
div.appendChild(button);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I think I see where you are going with this, add and remove hobbies.
Note for simplicity I wrap each group in a span, then add/remove that span.
I did NOT put a remove on the first one, you might do that IF you wanted to make it removable.
const addHobby = document.getElementById("add");
var i = 0;
const hobbydiv = document.getElementById("hobby");
addHobby.addEventListener("click", function() {
i++;
const newspan = document.createElement('span');
newspan.className = "groupthing";
const removeButton = document.createElement('button');
removeButton.addEventListener('click', function(e) {
e.target.closest(".groupthing").remove();
});
removeButton.className = "deleteus";
removeButton.innerHTML = "X";
const editInput = document.createElement('input');
editInput.id = i;
editInput.placeholder = "More hobbies";
newspan.appendChild(editInput);
newspan.appendChild(removeButton);
hobbydiv.appendChild(newspan);
});
.deleteus{color:red;}
<div id="hobby">
<span class="groupthing">
<input placeHolder="Type your hobby" />
<button class="deleteus">X</button>
</span>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
To add button,
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function () {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
btn.id = i;
var t = document.createTextNode("X");
btn.appendChild(t);
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
btn.addEventListener("click", function () {
div.removeChild(document.getElementById(btn.id));
div.removeChild(btn);
});
});

Categories