Adding UL using DOM Manipulation Not Working. Help is appreciated - javascript

<!DOCTYPE html>
<html>
<head>
<title>Learning About Nodes</title>
</head>
<body>
<ul>
<li>Hammerhead</li>
<li>Tiger</li>
<li>Great White</li>
</ul>
<button id="btn">Just do it</button>
</body>
</html>
btnElement = document.getElementById("#btn");
if (btnElement) {
btnElement.addEventlistener("click", justdoitFunction);
}
function justdoitFunction() {
const ul2 = document.createElement("ul");
document.body.appendChild(ul);
const listElement = document.createElement("li");
listElement.textContent = "This is done by Panda.";
ul2.appendChild(listElement);
}
I am trying to add a text content using the just do it button. I don't see what the mistake is. Help is greatly appreciated.

I have found some syntax errors, so i fixed it here:
const btnElement = document.getElementById("btn");
function justdoitFunction() {
const ul = document.createElement("ul");
document.body.appendChild(ul);
const listElement = document.createElement("li");
listElement.textContent = "This is done by Panda.";
ul.appendChild(listElement);
}
if (btnElement) {
btnElement.addEventListener("click", justdoitFunction);
}
But I can see that you are trying to insert an item into a ul list. Instead of creating a new whole list each time you click the button, try to select the existing list and add the item there:
<!DOCTYPE html>
<html>
<head>
<title>Learning About Nodes</title>
</head>
<body>
<ul id="list">
<li>Hammerhead</li>
<li>Tiger</li>
<li>Great White</li>
</ul>
<button id="btn">Just do it</button>
</body>
</html>
const btnElement = document.getElementById("btn");
function justdoitFunction() {
const ul = document.getElementById("list");
const listElement = document.createElement("li");
listElement.textContent = "This is done by Panda.";
ul.appendChild(listElement);
}
if (btnElement) {
btnElement.addEventListener("click", justdoitFunction);
}

Related

How To Hide An Input Field

I can't seem to get my to-do list working. I've been following a tutorial on YouTube and after writing out all the code, nothing seems to be added/displayed if I attempt to add something to the to-do list. I've had a good look through everything and also rewatched the video and double checked I had the exact same code (the video doesn't provide the source code). I'm lost at this point and would appreciate any help.
The functionality of the project should allow people to add something to the to-do list, edit items they have in their list and also be able to delete their item.
Is there any way to not have the input field display after adding an entry, until the user clicks the "edit" button? When I add an entry, not only does it show what I had entered, it also displayed the input field to edit the entry like so:
// Add To-Do's
var add_todo_btn = document.getElementById('add-btn');
var todo_input = document.getElementById('todo-input');
var list = document.getElementById('list');
add_todo_btn.addEventListener('click', function () {
var todo = todo_input.value;
var item = document.createElement('DIV');
item.classList.add('item');
var item_text = document.createElement('DIV');
item_text.classList.add('item-text');
item_text.textContent = todo;
var edit_input = document.createElement('INPUT');
edit_input.classList.add('edit-input');
edit_input.classList.add('hide');
edit_input.name = 'edit-input';
edit_input.type = 'text';
edit_input.value = todo;
var edit_input_btn = document.createElement('BUTTON');
edit_input_btn.textContent = 'UPDATE';
edit_input_btn.classList.add('action-btn');
edit_input_btn.classList.add('update-btn');
edit_input_btn.classList.add('hide');
edit_input_btn.type = 'button';
var action_btns = document.createElement('DIV');
action_btns.classList.add('action-btns');
var edit_btn = document.createElement('BUTTON');
edit_btn.classList.add('action-btn');
edit_btn.classList.add('edit-btn');
edit_btn.textContent = 'EDIT';
// Edit To-Do's
edit_btn.addEventListener('click', function () {
edit_input.classList.remove('hide');
item_text.classList.add('hide');
edit_input_btn.classList.remove('hide');
edit_input_btn.addEventListener('click', function () {
item_text.textContent = edit_input.value;
edit_input.classList.add('hide');
item_text.classList.remove('hide');
edit_input_btn.classList.add('hide');
});
});
var remove_btn = document.createElement('BUTTON');
remove_btn.classList.add('action-btn');
remove_btn.classList.add('remove-btn');
remove_btn.textContent = 'REMOVE';
// Remove To-Do's
remove_btn.addEventListener('click', function () {
item.parentNode.removeChild(item);
});
action_btns.append(edit_input_btn);
action_btns.append(edit_btn);
action_btns.append(remove_btn);
item.append(item_text);
item.append(edit_input);
item.append(action_btns);
list.append(item);
todo_input.value = '';
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<title>Todo App</title>
</head>
<body>
<div class="app">
<div class="header">
<div class="title">To-Do List</div>
</div>
<div class="input">
<input type="text" name="todo-input" id="todo-input" class="input-element" placeholder="What do you need to do?" />
<button type="button" name="add-btn" id="add-btn" class="input-btn">
Add
</button>
<div class="todo-list" id="list"></div>
</div>
</div>
</body>
</html>
It looks like you're already adding a "hide" class in the correct circumstances - you just need to define the css for this class:
.hide{
display: none;
}
Once you add this, the example functions as you would expect:
// Add To-Do's
var add_todo_btn = document.getElementById('add-btn');
var todo_input = document.getElementById('todo-input');
var list = document.getElementById('list');
add_todo_btn.addEventListener('click', function () {
var todo = todo_input.value;
var item = document.createElement('DIV');
item.classList.add('item');
var item_text = document.createElement('DIV');
item_text.classList.add('item-text');
item_text.textContent = todo;
var edit_input = document.createElement('INPUT');
edit_input.classList.add('edit-input');
edit_input.classList.add('hide');
edit_input.name = 'edit-input';
edit_input.type = 'text';
edit_input.value = todo;
var edit_input_btn = document.createElement('BUTTON');
edit_input_btn.textContent = 'UPDATE';
edit_input_btn.classList.add('action-btn');
edit_input_btn.classList.add('update-btn');
edit_input_btn.classList.add('hide');
edit_input_btn.type = 'button';
var action_btns = document.createElement('DIV');
action_btns.classList.add('action-btns');
var edit_btn = document.createElement('BUTTON');
edit_btn.classList.add('action-btn');
edit_btn.classList.add('edit-btn');
edit_btn.textContent = 'EDIT';
// Edit To-Do's
edit_btn.addEventListener('click', function () {
edit_input.classList.remove('hide');
item_text.classList.add('hide');
edit_input_btn.classList.remove('hide');
edit_input_btn.addEventListener('click', function () {
item_text.textContent = edit_input.value;
edit_input.classList.add('hide');
item_text.classList.remove('hide');
edit_input_btn.classList.add('hide');
});
});
var remove_btn = document.createElement('BUTTON');
remove_btn.classList.add('action-btn');
remove_btn.classList.add('remove-btn');
remove_btn.textContent = 'REMOVE';
// Remove To-Do's
remove_btn.addEventListener('click', function () {
item.parentNode.removeChild(item);
});
action_btns.append(edit_input_btn);
action_btns.append(edit_btn);
action_btns.append(remove_btn);
item.append(item_text);
item.append(edit_input);
item.append(action_btns);
list.append(item);
todo_input.value = '';
});
.hide{
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<title>Todo App</title>
</head>
<body>
<div class="app">
<div class="header">
<div class="title">To-Do List</div>
</div>
<div class="input">
<input type="text" name="todo-input" id="todo-input" class="input-element" placeholder="What do you need to do?" />
<button type="button" name="add-btn" id="add-btn" class="input-btn">
Add
</button>
<div class="todo-list" id="list"></div>
</div>
</div>
</body>
</html>
You can add 'readonly' inline to your input tag. This will display your input field as is but the user won't be able to edit the content of the input tag. If you want to hide the input field, simply change the display style to none, i.e. display: none; .
You can create a JavaScript function that modifies the styling of these elements onClick.

I'm trying to get the parent of the parent (div) of the li-element which I click

I'm trying to get the parent of the parent (div) of the li-element which I click and change/remove it's class but I don't know how to tell JS that it should get the specific li class that I click. Sorry for this simple question I'm fairly new to JS.
<!DOCTYPE html>
<html>
<body>
<p>List:</p>
<div class="div">
<ul>
<li class="lis">Coffee</li>
<li class="lis">Tea</li>
<li class="lis">Water</li>
</ul>
</div>
<script>
let li = document.getElementsByClassName("lis")
li.click() = function() {
var x = li.parentElement.parentElement.classList.value
if(x.classList.contains("div")) {
x.remove.classList("div")
}
}
</script>
</body>
</html>
<script>
var elements = document.getElementsByClassName("lis");
var myFunction = function(e) {
x = e.target.innerHTML;
e.target.parentElement.parentElement.innerHTML=x
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
</script>
You can use .closest() to select the closest div and after that, you can remove the class from that element.
Try below working code -
var elements = document.getElementsByClassName("lis");
var myFunction = function() {
var x = this.closest('.div')
if (x) {
this.closest('.div').classList.remove("div")
console.log('Div Element Class Removed!');
}
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
<!DOCTYPE html>
<html>
<body>
<p>List:</p>
<div class="div">
<ul>
<li class="lis">Coffee</li>
<li class="lis">Tea</li>
<li class="lis">Water</li>
</ul>
</div>
</body>
</html>
I recommend to delegate to the nearest static container
Also you had remove.classList - that should be classList.remove
Here I give an ID to the UL and test if the LI clicked has the lis class
document.getElementById("ul").addEventListener("click",function(e) {
const tgt = e.target.closest("li")
if (tgt.classList.contains("lis")) {
tgt.closest("div").classList.remove("div")
}
})
.div { background-color:red }
<p>List:</p>
<div class="div">
<ul id="ul">
<li class="lis">Coffee</li>
<li class="lis">Tea</li>
<li class="lis">Water</li>
</ul>
</div>
I came up with another good solution that let's me add and remove the div class, the parent of specified li elements. I added an extra div to make sure it always gets the certain parent that I've specified with .closest(body > div) and used a for loop to make the array that it creates select one certain li element, the one I currently click on.
<!DOCTYPE html>
<html>
<body>
<p>List:</p>
<div class="div">
<ul>
<li class="lis">Coffee</li>
<li class="lis">Tea</li>
<li class="lis">Water</li>
</ul>
</div>
<div>
<ul>
<li class="l">Coffee</li>
<li class="l">Tea</li>
<li class="l">Water</li>
</ul>
</div>
<script>
let lists = document.getElementsByClassName("lis");
let divs = document.getElementsByTagName("div");
for (let list of lists) {
list.addEventListener("click", () => {
list.closest("body > div")
for (let div of divs) {
div.addEventListener("click", () => {
if (div.classList.contains("div")) {
div.classList.remove("div")
} else {
div.classList.add("div")
}
})
}
})
}
</script>
<style>
.div {
color: brown;
font-size: larger;
}
</style>
</body>
</html>
var li = document.getElementsByClassName("lis");
for (var i=0; i<li.length; i++) {
li[i].onclick = function() {
var el = this.parentElement.parentElement;
if (el.className == "div") {
el.className = "";
}
}
}

How to add and delete object in javascript?

I have order list in HTML :
<ol id="myList">
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
And Ii write code in Javascript, and now I can add one item in this list. I have also set up limit of adding items. When I add one items, then how can I delete it?
<script>
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
</script>
You could add remove button to every item in the list and attach onclick event to it that will call removeItem() function, check example below.
Hope this helps.
Snippet
var limit = 1
var currentAmount = 0;
function myFunction() {
//Check we haven't reached our limit.
if(currentAmount < limit){
var x = document.createElement("li");
var remove_btn = document.createElement("input");
remove_btn.setAttribute("type", "button");
remove_btn.setAttribute("value", "X");
remove_btn.setAttribute("onclick", "removeItem(this)");
x.appendChild(remove_btn);
var t = document.createTextNode("Coffee");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
currentAmount++; //Increment our count
}
}
function removeItem() {
event.target.parentNode.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol id="myList">
<li><button onclick="removeItem(this)">X</button> Tea</li>
<li><button onclick="removeItem(this)">X</button> Milk</li>
<li><button onclick="removeItem(this)">X</button> Water</li>
</ol>
<button onclick="myFunction()">Try it</button>
Well, it depends which element you want to remove, but for example, to remove the last element, add this button:
<button onClick="removeItem();">Now try this</button>
and this script:
function removeItem() {
document.getElementById("myList").lastChild.remove();
}
Got carried away, it removes items as OP requested and it:
Generates the delete button for every list item.
Added delete buttons for the old list items.
Added a text input so the user can input the list items.
Added an eventListener to the list in order to handle which button was clicked and save memory having one eventListener instead of one for each button.
Snippet
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Shopping List</title>
<style>
#inp1 {
margin: 10px 15px;
width: 25ex;
}
.item {
max-width: 30ex;
position: relative;
}
.del {
line-height: 1;
width: 7ex;
margin: 0 20px;
padding: 0 3px;
position: absolute;
right: -10px;
}
.del:before {
content: 'Delete';
font: inherit;
}
</style>
</head>
<body>
<h2>Shopping List</h2>
<ol id="list">
<li class="item">Tea
<button class="del"></button>
</li>
<li class="item">Milk
<button class="del"></button>
</li>
<li class="item">Water
<button class="del"></button>
</li>
</ol>
<input id="inp1" name="inp1" placeholder="Grocery Item" />
<button onclick="list(inp1.value)">Add</button>
<script>
var limit = 6
var currentAmount = 3;
var ol = document.getElementById("list");
function list(item) {
//Check we haven't reached our limit.
if (currentAmount < limit) {
var li = document.createElement("li");
var str = document.createTextNode(item);
var btn = document.createElement('button');
li.appendChild(str);
li.appendChild(btn);
li.classList.add('item');
btn.classList.add('del');
ol.appendChild(li);
currentAmount++; //Increment our count
}
return false;
}
ol.addEventListener('click', function(event) {
if (event.target != event.curentTarget) {
var tgt = event.target;
var li = tgt.parentElement;
ol.removeChild(li);
currentAmount--;
}
event.stopPropagation();
}, false);
</script>
</body>
</html>

ParentNode and insertBefore

I created a prompt box with a question. After answering, you receive the answer in a div created with JavaScript called id2. Now I am trying to place my id2 in front of id1 which is the parentNode. So it will show the answer above the first div id1. Can someone explain to me why it's not working?
<!DOCTYPE html>
<html>
<head>
<title>lab7</title>
<meta charset="utf-8" lang="en" name="my page" />
<style>
.class1 {
width: 100%;
height: 60px;
background-color: #BCC6CC;
}
</style>
<script type="text/javascript">
function loadQ() {
var firstdiv = document.createElement("div");
firstdiv.setAttribute("class", "class1");
firstdiv.setAttribute("id", "id1");
var jw = prompt("Which movie is number 1 Box Office 2015?","Jurassic World");
document.getElementById("id2").innerHTML ="" + jw + " Made $652,198,011 Total Gross Sales";
document.getElementById("id2").style.backgroundColor = "#786D5F";
var id1 = document.getElementByTagName("div")[0];
var parent1 = id1.parentNode();
var beforeME = document.getElementByTagName("id2");
parent1.insertBefore(id1, beforeME);
};
</script>
</head>
<body onload="loadQ()">
<div id="id1" class="class1">
<br>
<b>Top 2 Box Office Movie for 2015</b>
</div>
<div class="class2" id="id2">
</div>
</body>
</html>
There are at least two issues in your code:
document.getElementsByTagName needs an s (it returns multiple elements).
To get an object by id, you need to use document.getElementById.
I rewrote my code and made it more clear. So, each div id and class are define.
<script type="text/javascript">
function loadQ() {
var firstdiv = document.createElement("div");
firstdiv.setAttribute("class", "class1");
firstdiv.setAttribute("id", "id1");
firstdiv.style.backgroundColor = "#BCC6CC;";
document.getElementById('id1').innerHTML ="<h2 style='padding:20px;'>Top Box Office Movie 2015</h2>","<br><br>";
var seconddiv = document.createElement("div");
seconddiv.setAttribute("class", "class2");
seconddiv.setAttribute("id", "id2");
seconddiv.style.backgroundColor = "#786D5F";
var reper = document.getElementById('id1');
var parinte = reper.parentNode;
parinte.insertBefore(seconddiv, reper);
</script>

how to use addEventListener to get list of elements?

Can someone help out here? i have this project going on... i want that when the list items in the 'players' array are clicked, they should move to the 'actual-players' list. i want to use an event listener.... below are my codes...
JAVASCRIPT
function init(){
var players = ["Player1", "Player2", "Player3", "Player4",
"Player5"];
var listItems = document.getElementById("first");
for (var i = 0; i < players.length; i++){
var newPlayersList = document.createElement("li");
newPlayersList.ClassName = "list-item";
var listItemsValue = document.createTextNode(players[i]);
newPlayersList.appendChild(listItemsValue);
listItems.appendChild(newPlayersList);
}
//Below is where i write the codes to set the elements of the 'players' array to move to the 'actual-players' list. But it doesn't work!
var players = document.getElementsByClassName("list-item");
for(var i=0; i<players.length; i++){
players[i].addEventListener("click", function(){
var text = this.innerHTML;
var liElement = document.createElement("li");
liElement.ClassName = "test";
var text = document.createTextNode(text);
liElement.appendChild(text);
var lis = document.getElementById("actual-
players").getElementsByTagName("li");
if (lis.length == 4){
alert("Don't let more than four players");
} else {
document.getElementById("actual-
players").appendChild(liElement);
this.remove();
}
});
}
}
window.onload = function(){
init();
};
HTML
<html>
<head>
<title>Table Soccer Teams</title>
<link rel="stylesheet" type="text/css" href="soccer.css" />
<script type="text/javascript" src="table_soccer.js" ></script>
</head>
<body>
<a id="reset" href="javascript:location.reload(true)"
class="btn">Reset</a>
<div id="soccer_field">
<div class="players" onsubmit="return(validateForm ());">
<h2>Possible Players</h2>
<ul id="first"></ul>
<p class="one">Click on names above <br>to select actual
players</p>
</div>
<div class="actual_players">
<h3>Actual Players</h3>
<ul id="actual-players" ></ul>
<p class="two">Click button below to <br>generate Teams</p>
<br>
<a id="generate" href ="#" class="btn">Click here</a>
</div>
</div>
</body>
</html>

Categories