How to remove certain element from my list Javascript html - javascript

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>ToDo</title>
</head>
<body>
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br>
<br>
<input type="text" id="toDo">
<br>
<br>
<button type="button" id="myButton">Submit</button>
<button type="button" id="clearList">Clear List</button>
<br>
<ul id="list"></ul>
<script src="todojs.js"></script>
</body>
</html>
JAVASCRIPT
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li = '<li id="item">' + doIt + '<button type="button" id="clearOne">X</button>' + '</li>';
document.getElementById('list').insertAdjacentHTML('beforeend', li);
document.getElementById('toDo').value = '';
document.getElementById('clearList').onclick = function() {
const ul = document.getElementById('list');
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
}
document.getElementById('clearOne').onclick = function () {
const currentLi = document.getElementById('item');
currentLi.removeChild();
}
}
SO im putting a X next to each to do and i want to be able to remove the one LI element when the user presses the X but i keep failing i tried multiple things cants figure it out

I think this what you are looking for.
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
// create li element.
const li = document.createElement('li');
li.innerText = doIt;
// create remove button.
const removeButton = document.createElement('button');
// Set text of remove button
removeButton.innerText = 'X';
// Add event listener for the remove button.
removeButton.addEventListener('click', function() { this.parentNode.remove() } )
// append the button inside the li element
li.append(removeButton);
// prepend the li element in the list.
document.getElementById('list').prepend(li);
document.getElementById('toDo').value = '';
document.getElementById('clearList').onclick = function() {
const ul = document.getElementById('list');
ul.innerHTML = '';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>ToDo</title>
</head>
<body>
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br>
<br>
<input type="text" id="toDo">
<br>
<br>
<button type="button" id="myButton">Submit</button>
<button type="button" id="clearList">Clear List</button>
<br>
<ul id="list"></ul>
<script src="todojs.js"></script>
</body>
</html>

An easy way would be:
function remove(el) {
el.parentElement.remove();
}
document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li = '<li id="item">' + doIt + '<button type="button" onClick="remove(this)" id="clearOne">X</button>' + '</li>';
document.getElementById('list').insertAdjacentHTML('beforeend', li);
document.getElementById('toDo').value = '';
}

First of all,
You should not use the same id for multiple elements. You are assigning id of "item" to every li element. So when you try to remove the element by id it will not work as expected.
Assign a unique id to every li element (you can also use unique classes or custom refs. But let's use ids).
<li id="some_unique_id">todo </li>
I think we will have to use classes and custom data attributes on the buttons to achieve what we want.
Ex: <button class="removeBtn" data-todoid="_the_corresponding_todo_id_">Remove</button>
Here we use the data-todoid attribute value to identify which li element will remove when we click this.
Let's modify your code now.
document.getElementById('myButton').onclick = function () {
// as we need some string or number to use as a unique id,
// its better to use the current timestamp in milliseconds in here.
const thiselementuniqueid = (new Date().getTime()).toString();
const doIt = document.getElementById('toDo').value;
const li = '<li id="todoitem_"+thiselementuniqueid >' + doIt + '<button type="button"
class="clearBtn" data-todoid="todoitem_"+thiselementuniqueid >X</button>' + '</li>';
document.getElementById('list').insertAdjacentHTML('beforeend', li);
document.getElementById('toDo').value = '';
// get all the li remove buttons
var clearButtons = getElementsByClassName('clearBtn');
// write on click event action for all of them
for(var a = 0; a<clearButtons.lenth;a++){
var asinglebutton = clearButtons[a]; // selected a button
asinglebutton.onClick = function(){
let todoid = $(this).data("todoid"); // get matching todo id to be removed on click
let currentLi = document.getElementById(todoid);
currentLi.removeChild();
}
}
document.getElementById('clearList').onclick = function() {
const ul = document.getElementById('list');
ul.innerHtml = "";
}
I haven't tested this. But this is the best approach in your case.
Edit : Leonardo's above answer is much simpler, easy, and quick. Try it.

Related

li element stored on local stotarge doesn't show off on the screen

I'm working on a project where I need to ask the user for an input and when the user clicks on the button the input get stored in local storage and displays on the screen, I want each time that the user gets on the page the input show off as a li element, but the problem is that the input shows off on the document only once, while refreshing the page, the li element disappears but the key and the value are still stored on the Local Storage.
Here's a part of my JavaScript.
const input = document.querySelector('#text-input');
const addBtn = document.querySelector('#add-plan-btn');
const ol = document.querySelector('ol');
addBtn.addEventListener('click', displayInput);
function displayInput(){
// this function shows the input on an li element
let li = document.createElement('li');
window.localStorage.setItem('plan', input.value);
li.textContent = localStorage.getItem('plan');
ol.appendChild(li);
}
here's my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="container">
<h1>Plan Maker</h1>
<div class="input-plan">
<input type="text" id="text-input" placeholder="enter here...">
<button type="submit" id="add-plan-btn">Add</button>
</div>
<ol></ol>
</div>
<script src="script.js"></script>
</body>
</html>
Thanks in advance.
First you need to save ol.innerText in local storage and on page load you may need to check if local storage has value, create some li based on storage value and append to ol tag
Try this one:
const input = document.querySelector('#text-input');
const addBtn = document.querySelector('#add-plan-btn');
const ol = document.querySelector('ol');
addBtn.addEventListener('click', displayInput);
var data = localStorage.getItem('plan');
if (data) {
var lst = data.split("\n");
lst.forEach(t => ol.innerHTML += "<li> " + t + "</li>");
}
function displayInput() {
// this function shows the input on an li element
let li = document.createElement('li');
li.textContent = input.value;
ol.appendChild(li);
window.localStorage.setItem('plan', ol.innerText);
}

My EDIT button is not working properly? (Javascript Todo List) Beginner

I am a beginner in Javascript and is currently trying to make a todo list web app. But currently stucked at the edit button.
As you can see, I wanted to make an editable checklist but somehow everytime I hit the edit button, a new input comes out instead of replacing the current one. It also removes the 'checkbox' somehow.
Can anyone tell me where I did wrong? Thank you for your time!
Somehow the edit button doesn't work at all when I try to run it on VSCode. Here it works, but not as I wanted though.
const ul = document.querySelector('#invitedList');
ul.addEventListener('click', (event) => {
if(event.target.tagName === 'BUTTON') {
const button = event.target;
const li = button.parentNode;
if(button.textContent === 'edit') {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
} else if(button.textContent === 'save') {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="test.js"></script>
</head>
<body>
<!-- TASK LIST THAT IS SUPPOSED TO BE EDITABLE GOES DOWN HERE, AS A TEMPLATE -->
<div id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>
Have you considered trying Node.ReplaceChild() instead of creating a new element? Not sure how to tell you exactly how to do it but here is a link to the documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
I'd suggest to change styling instead of creating and removing elements. Here is possible solution:
let isEditState = false;
const editButton = document.querySelector('#editbtn');
editButton.addEventListener('click', (event) => {
const span = document.querySelector('#editable');
const checkbox = document.querySelector('#checkbox');
const text = document.querySelector('#text');
if (isEditState) {
span.innerText = text.value;
checkbox.style.display = 'inline';
text.style.display = 'none';
editButton.innerText = 'edit';
} else {
checkbox.style.display = 'none';
text.style.display = 'inline';
editButton.innerText = 'save';
}
isEditState = !isEditState;
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox" id="checkbox"/>
<input type="text" id="text" style="display: none"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>

Value from Input box not showing

So I am trying to create a simple to-do application. The list itself works perfectly fine and things get added how they should.
However, now I am trying to have a sort of timeline that basically shows the todo items in a different style.
Now the issue is every time an item gets added, it shows up in the regular checklist but not in the new timeline. The LI gets created but with no content inside of it.
Any of you guys know how I can display the input value from the input box into the timeline as I did with the regular checklist?
let inputValue = document.getElementById("inputValue");
let addButton = document.getElementById("addButton");
let frm = document.querySelector("form");
//Prevent Refresh
function handleForm(event) {
event.preventDefault();
}
function addItem() {
// Check Input for empty value
if (inputValue.value.length == 0) {
alert("Your Input was empty");
return;
}
//Create LI and append to UL
let listItem = document.createElement("li");
listItem.innerText = inputValue.value;
let ul = document.getElementById("list-ul")
ul.appendChild(listItem);
listItem.className = "list-item";
//Create Delet button and append to LI
let deleteButton = document.createElement("button");
listItem.appendChild(deleteButton);
deleteButton.className = "delete-button";
deleteButton.innerHTML = '<i class="far fa-trash-alt"></i>';
deleteButton.addEventListener("click", deleteItem);
//Reset the Input
frm.reset();
//Prevent refresh
frm.addEventListener('submit', handleForm);
//Delete Function
function deleteItem(e) {
console.log("Item deleted");
listItem.remove();
}
//Timeline
let timeline = document.getElementsByClassName("timeline");
let timeUl = document.getElementById("time-ul");
//Create LI for timeline
let timelineItem = document.createElement("li");
timelineItem.innerText = inputValue.value;
timeUl.appendChild(timelineItem);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/e7a951e13e.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#100;200;300;400;500;600;700;800&display=swap" rel="stylesheet">
<title>Document</title>
</head>
<body>
<main>
<div class="container">
<h1>To Do</h1>
<form>
<input type="text" id="inputValue">
<button type="button" id="addButton" onclick="addItem();">Add Item</button>
<!-- <button type="button" id="clearAll" onclick="clearAll();">Clear All</button> -->
</form>
<div id="list-container">
<ul id="list-ul">
</ul>
</div>
<div class="timeline">
<ul id="time-ul">
</ul>
</div>
</div>
</main>
<script src="index.js"></script>
</body>
</html>
You are reseting the form and later trying to access the value from the input, which was cleared.
Move frm.reset(); to after the Timeline is updated.
...
//Timeline
let timeline = document.getElementsByClassName("timeline");
let timeUl = document.getElementById("time-ul");
//Create LI for timeline
let timelineItem = document.createElement("li");
timelineItem.innerText = inputValue.value;
timeUl.appendChild(timelineItem);
//Reset the Input
frm.reset();
Another option you have is to store the input value in a variable and use it in your calls before resetting the form.
const todoValue = inputValue.value;
...
//Timeline
timelineItem.innerText = todoValue;
Alright, i was just blind and forgot that i cleared the input by resetting the form.

Adding an 'active-class' to a list which is inputted by user

Hello im new to Javascript and trying out some different things.
I have a ul which the user can input some li:s.
My goal is to set a li class of active and then removing it by referencing it to the active class. Like a To-Do list but light.
I've tried alot of different approaches and the code below is what I got right now which isn't working properly... The first function just adds things to the list and the second should give a li element the class of active.
The removing part I'm hoping to solve by myself..
Im very thankful for any input. Thanks!
function addElementLast (){
let textValue = document.getElementById('candidate').value;
if(textValue == ''){
alert('Type something')
}else{
let newLi = document.createElement('li')
newLi.setAttribute('class', 'toggle');
let get = document.getElementsByTagName('ul')[0];
let textNode = document.createTextNode(textValue);
newLi.appendChild(textNode);
get.appendChild(newLi);
}}
var parent = document.getElementById("dynamic-list");
var child = parent.getElementsByClassName("toggle");
for (var i = 0; i < child.length; i++) {
child[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className += " active";
});
}
document.getElementById('btn').addEventListener('click', addElementLast)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Adding to ul</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2 id="heading" class="text-center">Adding to UL</h2>
<ul id="dynamic-list">
</ul>
<input type="text" id="candidate" placeholder="Write here">
<button type="button" id="btn" class="btn btn-success">Add item</button>
<button type="button" id="btn1" class="btn btn-danger">Remove item</button>
</div>
<script src="script.js"></script>
</body>
</html>
I think you'd be better off if you manipulated a list in JS and just rendered an HTML "template" to the UI.
It's faster, easier to keep track of items and much easier to change the algorithms.
let todoList = []
// adding to the todo list
function addTodo(s, arr) {
if (s) {
arr.push({
text: s,
active: false
})
}
return arr
}
// creating the html that should be rendered
function createTodoListHTML(arr) {
let html = ''
arr.forEach(e => {
const active = e.active ? ' active' : ''
html += `<li class="item${active}">${e.text}</li>`
})
return html
}
// rendering the list
function displayTodoList(html) {
document.getElementById('dynamic-list').innerHTML = html
activate(todoList)
}
// handling add item btn click
document.getElementById('btn').addEventListener('click', function(e) {
let input = document.getElementById('candidate')
addTodo(input.value, todoList)
displayTodoList(createTodoListHTML(todoList))
input.value = ''
})
// adding event listener to li items
function activate(list) {
const children = document.querySelectorAll('#dynamic-list .item')
children.forEach((e, i) => {
e.addEventListener('click', function(el) {
todoList[i].active = !todoList[i].active
displayTodoList(createTodoListHTML(todoList))
})
})
}
// removing items from the list and the UI
const btnRemove = document.getElementById('btn1')
btnRemove.addEventListener('click', function(e) {
todoList = removeItems(todoList)
displayTodoList(createTodoListHTML(todoList))
})
function removeItems(arr) {
return arr.filter(e => !e.active)
}
.active {
font-weight: 700;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container">
<h2 id="heading" class="text-center">Adding to UL</h2>
<ul id="dynamic-list">
</ul>
<input type="text" id="candidate" placeholder="Write here">
<button type="button" id="btn" class="btn btn-success">Add item</button>
<button type="button" id="btn1" class="btn btn-danger">Remove item</button>
</div>
<script src="script.js"></script>

Is it possible to remove the child elements of the Ul I have with my code?

On each click of the deleteButton, I want to be able to remove the span and li element from my ul. Here is my code:
let textArea = document.getElementById('textArea');
let submit = document.getElementById("submit")
let ul = document.getElementById("task-list");
let deleteButton = document.getElementsByClassName("deleteButton");
//add todo
submit.addEventListener("click", function(){
let listItem = document.createElement("li");
let val = textArea.value;
listItem.innerHTML = `<button class="deleteButton">X</button> ${val}`;
ul.appendChild(listItem);
textArea.value = "";
});
//delete todo
deleteButton.addEventListener("click", function(){
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://kit.fontawesome.com/1f5460a8a6.js"></script>
<link rel="stylesheet" href="style.css">
<title>Todo List</title>
</head>
<body>
<div id="container">
<h1>To-do List</h1>
<input type="text" id="textArea"><button id="submit">+</button>
<ul id="task-list">
</ul>
</div>
<script src="script.js"></script>
</body>
</html>
Is it possible with something like I have setup here? Sorry about asking, but I am just stuck and want to become unstuck. I am thinking that using removeChild may work. However, I don’t think it can take both the span and li elements away at the same time.
You would have to attach an eventHandler on each instance of a delete-button, which you can't the way you're trying, because it's a nodeList and not a single element. I would suggest doing it within the eventHandler on 'submit', like so:
submit.addEventListener("click", function(){
let listItem = document.createElement("li");
let val = document.createTextNode(textArea.value);
let btn = document.createElement('button');
btn.textContent = 'X';
btn.onclick = e => e.target.parentNode.remove();
listItem.append(btn, val);
ul.appendChild(listItem);
textArea.value = "";
});
Try this. Hope it will work.
document.querySelector("ul").addEventListener("click", function(e) {
var element = e.target;
element.remove()
});

Categories