How to replace content of div element? - javascript

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>

Related

How to change a div to textarea and vice versa with only vanilla javascript without using jquery?

how to change a div to a textarea to edit the text in the div when a button is clicked and the same button is clicked again then that textarea change to a div.
HTML
<button class="button">click me</button>
<div class="div">this is div or textarea</div>
JS
const button = document.querySelector('button');
const div = document.querySelector('div');
let isTextarea = false
button.addEventListener('click', () => {
if(isTextarea) {
const div = document.createElement('div')
const textarea = document.createElement('textarea')
div.innerHTML = textarea.value
textarea.parentNode.replaceChild(div, textarea)
isTextarea = false
}else {
const textarea =document.createElement('textarea')
textarea.innerHTML = div.innerHTML
div.parentNode.replaceChild(textarea, div)
isTextarea = true
}
} )
You do not need to create both a <div> and a <textarea> in both branches. If you have a textarea, all you need to create is a div, and if you have a div, all you need to create is a textarea. (Referencing the textarea.parentNode of an element you just created and haven't appended anywhere throws an error, as expected - that doesn't make sense.)
You'll need to either select the existing <div> or <textarea> in the document
const button = document.querySelector('button');
let isTextarea = false
button.addEventListener('click', () => {
if (isTextarea) {
const div = document.createElement('div');
const textarea = document.querySelector('textarea');
div.innerHTML = textarea.value;
textarea.parentNode.replaceChild(div, textarea);
isTextarea = false;
} else {
const textarea = document.createElement('textarea');
const div = document.querySelector('div');
textarea.innerHTML = div.innerHTML;
div.parentNode.replaceChild(textarea, div)
isTextarea = true
}
})
<button class="button">click me</button>
<div class="div">this is div or textarea</div>
Or create both elements on pageload, but only append one initially.
const button = document.querySelector('button');
const div = document.body.appendChild(document.createElement('div'));
div.textContent = 'this is div or textarea';
const textarea = document.createElement('textarea');
let isTextarea = false
button.addEventListener('click', () => {
if (isTextarea) {
div.innerHTML = textarea.value;
textarea.parentNode.replaceChild(div, textarea);
isTextarea = false;
} else {
textarea.innerHTML = div.innerHTML;
div.parentNode.replaceChild(textarea, div)
isTextarea = true
}
})
<button class="button">click me</button>
You could also ditch the isTextarea flag if you wanted by checking which element .isConnected.
const button = document.querySelector('button');
const div = document.body.appendChild(document.createElement('div'));
div.textContent = 'this is div or textarea';
const textarea = document.createElement('textarea');
button.addEventListener('click', () => {
if (textarea.isConnected) {
div.innerHTML = textarea.value;
textarea.parentNode.replaceChild(div, textarea);
} else {
textarea.innerHTML = div.innerHTML;
div.parentNode.replaceChild(textarea, div)
}
})
<button class="button">click me</button>
You don't really need to replace the child unless there's some reason that the first child of the .div div must contain a particular thing. Just hide whichever one you don't need.
let div;
let textarea;
document.addEventListener('DOMContentLoaded', function() {
div = document.querySelector('.div > div');
textarea = document.querySelector('.div > textarea');
document.querySelector('button').addEventListener('click', () => {
div.classList.toggle('hidden')
textarea.classList.toggle('hidden')
} )
textarea.addEventListener('input', () => {
div.innerHTML = textarea.value
} )
})
.hidden {
display: none
}
<button class="button">click me</button>
<div class="div"><div class="hidden"></div><textarea></textarea></div>

Splitting a paragraph into an array and animating each contents of the array on button click

<div id="container">
<button id="button">Click!</button>
</div>
JS:
const container = document.querySelector("#container");
const button = document.querySelector("#button");
button.addEventListener("click", () => {
let para = document.createElement("p");
para.textContent = "Text message one. Text message two. Text message three.";
let strText = para.textContent;
let splitText = strText.split(".");
for (let i=0; i<splitText.length;i++) {
splitText.textContent += "<span>" + splitText[i] + "</span>";
}
container.appendChild(splitText[i]);
});
I AM STUCK! How can I write my code such that onclicking the button, the array components of the paragraph is shown(animated) on the div one after another ??
I know about the css animation and transition but I just don't know how to apply it here.
Do you mean something like this?
const container = document.querySelector("#container");
const button = document.querySelector("#button");
let idx = 0;
let sentnce = "Text message one. Text message two. Text message three.";
let texts = sentnce.split(".").slice(0, -1);
button.addEventListener("click", () => {
if (idx < texts.length) {
let p = document.createElement("p");
p.textContent = texts[idx];
container.appendChild(p);
++idx;
}
});
<div id="container">
<button id="button">Click!</button>
</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>

How put button into variable when it appears after page onload

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.

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