how to add new <li> to <ul> onclick with javascript - javascript

How do I add a list element to an existing ul using a function from an onclick? I need it to add to this type of list ...
<ul id="list">
<li id="element1">One</li>
<li id="element2">Two</li>
<li id="element3">Three</li>
</ul>
... another list item with the id "element4" and text "Four" under that. I tried this function but it doesn't work...
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
}
I don't know JQuery so Javascript only please. Thank you!!

You have not appended your li as a child to your ul element
Try this
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);
}
If you need to set the id , you can do so by
li.setAttribute("id", "element4");
Which turns the function into
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
li.setAttribute("id", "element4"); // added line
ul.appendChild(li);
alert(li.id);
}

You were almost there:
You just need to append the li to ul and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}

First you have to create a li(with id and value as you required) then add it to your ul.
Javascript ::
addAnother = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var children = ul.children.length + 1
li.setAttribute("id", "element"+children)
li.appendChild(document.createTextNode("Element "+children));
ul.appendChild(li)
}
Check this example that add li element to ul.

Just use innerHTML:
function function1() {
ul.innerHTML += `<li> four </li>`;
}

Related

Displaying an array in a UL using javascript

I need some help displaying my javascript array within a UL html element.
I have been trying to figure this out for the last 4 days and I am not getting it right.
See my code below:
function load() {
let favLanguages = ["html", "css", "javascript", "go", "ruby"];
// create ul element and set its attributes.
let ul = document.createElement("ul");
for (i = 0; i <= favLanguages.length; i++);
{
let li = document.createElement("li"); // create li element.
li.innerHTML = favLanguages[i]; // assigning text to li using array value.
document.getElementById(1);
ul.appendChild(li); // append li to ul.
}
}
html
<body onload="load()">
<h1>My favourite languages:</h1>
<ul id="1"></ul>
I would really appreciate any help
Thanks
You're pretty much there. You had a couple of issues:
You already have specified a ul element within your HTML. You don't need to re-create it again by doing document.createElement('ul'), just select the ul instead
You had your ul element's id as the number 1. When you tried to select the ul by doing document.getElementById(1)`, that will not work. You need to pass in the string of the id. I rename it to 'one' to fix it.
In your for(...) loop, you had a semi colon (;) after for(...);. That will not work. I removed the semi colon for you.
You last line of code ul.appendChild(li) is the only thing you need to do after you set your innerHTML. You already have the ul in the dom, so just append your new elements to that.
Example:
function load() {
const favLanguages = ["html", "css", "javascript", "go", "ruby"];
// Get a refrerence to the UL
const ul = document.getElementById('one');
for (i = 0; i <= favLanguages.length; i++) {
const li = document.createElement("li"); // create li element.
li.innerHTML = favLanguages[i]; // assigning text to li using array value.
ul.appendChild(li); // append li to ul.
}
}
load();
<h1>My favourite languages:</h1>
<ul id="one"></ul>
The second line has an inline comment disrupting the code on that line. So, the let ul = document.createElement("ul"); is not read by the JS engine. It can be fixed by moving the comment after the code.
Your for loop and your function declaration have a semicolon terminating it. Try fixing it like below:
function load() {
let favLanguages = ["html", "css", "javascript", "go", "ruby"]
let ul = document.createElement("ul"); // create ul element and set its attributes.
for (i = 0; i <= favLanguages.length; i++) { let li = document.createElement("li"); // create li element.
li.innerHTML = favLanguages[i]; // assigning text to li using array value.
document.getElementById(1);
ul.appendChild(li); // append li to ul.
}
}
window.onload = function(){
// init arr
let favLanguages = ["html", "css", "javascript", "go", "ruby"];
// get ul element after document loaded: window.onload
let ulNode = document.getElementById("a1");
// create ul element and set its attributes.
let ul = document.createElement("ul");
for (let i = 0; i < favLanguages.length; i++){
let li = document.createElement("li"); // create li element.
li.innerText = favLanguages[i]; //inrHTML if you have new element
ulNode.appendChild(li);
}
}
<h1>My favourite languages:</h1>
<ul id="a1"></ul>

How to use closest() in a proper way in js

Student here!
Lets say i have function append() which generates <li> items inside an <ol>,those li items contain 2 buttons,one for removing the <li> that lies within and one for creating the same item but inside itself this time,in order to make another list layer.
Both by using the closest() method.
i cant figure out how to use the ADD <button>,i can call it but i cannot it make it work the way i want to.
I get this :
But i want to get something like this :
this is how i'm trying to do it :
function append() {
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class=input><button class=add>ADD</button><button class=remove>REMOVE</button>`);
ol.append(li)
document.getElementById("ol1").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("li").remove();
if (tgt.classList.contains("add")) tgt.closest("li").appendChild(li);
})
}
<html>
<body>
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1">
</ol>
</body>
</html>
To number with 1., 1.1, 1.2, 2., 2.1, 3., you need to use CSS. The counters function, obtains the number of the li. Each time an ol appears, the counter is reset to 1.. When a li appears, the top counter is used, concatenated with the new next new number of the previous li.
ol {
counter-reset: item
}
li {
display: block;
}
li:before {
content: counters(item, ".") ". ";
counter-increment: item;
}
In the append function, we add the li... For this, we call another function, which we will call create_li() which does the creation of the li.
function append() {
document.querySelector("#ol1").append( create_li() )
}
In the create_li() function, we create the li and return it with return li. In li, we add the two button elements, add and remove, but instead of doing it through a string, we do it with the function we already know, that is to say, document.createElement(), and also, on each button, we can add una funciĆ³n que llamaremos button_click function, used to receive the click event through addEventListener.
function create_li(){
var li = document.createElement("li")
var add = document.createElement("button")
var remove = document.createElement("button")
li.innerHTML = "LIST ITEM <input class=input>"
add.className = "add"
remove.className = "remove"
add.innerHTML = "+"
remove.innerHTML = "-"
add.addEventListener("click",button_click)
remove.addEventListener("click",button_click)
li.appendChild(add)
li.appendChild(remove)
return li
}
The button_click function, what it does is create the ol and li structure. In addition, it detects if the button clicked is the add or remove.
function button_click(e) {
const tgt = e.target;
var litg = tgt.closest("li")
var oltg = litg.querySelector("ol")
if(oltg==null){
var ol = document.createElement("ol")
litg.appendChild(ol)
oltg = ol
}
if (tgt.classList.contains("remove")){
litg.remove()
}
if (tgt.classList.contains("add")){
oltg.appendChild( create_li() )
}
}
The HTML structure is based on the li has to be inside the ol, and each sublist has to have an ol inside the li.
<ol>
<li>
1.
<ol>
<li>1.1</li>
<li>1.2</li>
<li>1.3</li>
</ol>
</li>
<li>
2.
<ol>
<li>2.1</li>
<li>2.2</li>
<li>2.3</li>
</ol>
</li>
<li>
3.
<ol>
<li>3.1</li>
<li>3.2</li>
<li>3.3</li>
</ol>
</li>
</ol>
Finished code:
function button_click(e) {
const tgt = e.target;
var litg = tgt.closest("li")
var oltg = litg.querySelector("ol")
if(oltg==null){
var ol = document.createElement("ol")
litg.appendChild(ol)
oltg = ol
}
if (tgt.classList.contains("remove")){
litg.remove()
}
if (tgt.classList.contains("add")){
oltg.appendChild( create_li() )
}
}
function create_li(){
var li = document.createElement("li")
var add = document.createElement("button")
var remove = document.createElement("button")
li.innerHTML = "LIST ITEM <input class=input>"
add.className = "add"
remove.className = "remove"
add.innerHTML = "+"
remove.innerHTML = "-"
add.addEventListener("click",button_click)
remove.addEventListener("click",button_click)
li.appendChild(add)
li.appendChild(remove)
return li
}
function append() {
document.querySelector("#ol1").append( create_li() )
}
ol {
counter-reset: item
}
li {
display: block;
}
li:before {
content: counters(item, ".") ". ";
counter-increment: item;
}
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1"></ol>
This is probably what you want?
function append() {
var ol = document.getElementById("ol1");
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class="input"><button class="add" onclick="add(this)">ADD</button><button class="remove" onclick="remove(this)">REMOVE</button><ol></ol>`);
ol.append(li)
}
function add(e) {
var li = document.createElement("li");
li.innerHTML = (`LIST ITEM <input class="input"><button class="add" onclick="add(this)">ADD</button><button class="remove" onclick="remove(this)">REMOVE</button><ol></ol>`);
e.parentElement.getElementsByTagName("ol")[0].appendChild(li);
}
function remove(e) {
e.parentElement.parentElement.removeChild(e.parentElement);
}
<html>
<body>
<button id="btn1" onclick="append()">Append</button>
<ol id="ol1">
</ol>
</body>
</html>
Instead of using 'closest' in the add method, you can simply find the parent and append in that.
EG : tgt.parentNode().appendchild(childLi)

Existing li gets overridden in todolist instead of adding a new li

I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)
let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");
let addNewFunc = function () {
let name = ul.appendChild(addNew);
name.textContent = input.value
};
<h1>spooky</h1>
<input type="text" class="input">
<ul>
<li>1</li>
<li>2</li>
</ul>
let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNewFunc = function () {
let addNew = document.createElement("li");
addNew.innerHTML = input.value;
let name = ul.appendChild(addNew);
};
<h1>spooky</h1>
<input type="text" class="input"><button onclick='addNewFunc()'> add</button>
<ul>
<li>1</li>
<li>2</li>
</ul>
Create new li element everytime on the function call, add value to it then append to ul element.
A couple of issues.
1) Move let addNew = document.createElement("li"); inside the function. When it's outside the function you're just reusing the same element over and over. If that line is in the function, you create a new element each time the function is called.
2) Might be worth changing that function expression to a function declaration so that it works better as I was picking up the following error in JSFiddle when I was testing the code:
ReferenceError: can't access lexical declaration `addNewFunc' before initialization
let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let button = document.querySelector('button');
button.addEventListener('click', addNewFunc)
function addNewFunc() {
let addNew = document.createElement("li");
addNew.textContent = input.value;
ul.appendChild(addNew);
};
DEMO (I added a button for convenience)
It happens because you have stored ul element in a variable, so you're appending new child at the same position (ul parent is not updated with information about new elements in it).
Try with:
let addNewFunc = function () {
let name = document.querySelector("ul").appendChild(addNew);
};
You can create new li like this:
let addNewFunc = function () {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("option string"));
ul.appendChild(li);
};
Full code is
let input = document.querySelector(".input");
let ul = document.querySelector("ul");
input.onchange=function(){
let addNew = document.createElement("li");
addNew.innerHTML=this.value;
this.value="";
ul.appendChild(addNew);
}
This should help u.
please note: I have minute changes to your html; here u enter in inputbox and click button to add it to list
here is the fiddle : https://jsfiddle.net/5o2vwdqc/
html
<h1>spooky</h1>
<input type="text" class="input">
<button id="addToList">
Add to List
</button>
<ul id="theList">
<li>1</li>
<li>2</li>
</ul>
js
let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");
document.getElementById("addToList").onclick = function() {
let inputValue = document.getElementsByClassName("input")[0].value;
let addNew = document.createElement("li");
let textNode = document.createTextNode(inputValue);
addNew.appendChild(textNode);
document.getElementById("theList").appendChild(addNew);
}

addEventListener not working after appendChild

I have one ul, and add dynamically an option element and inside that option one anchor element.
The problem begins when I add an event on the anchor! Not working!
HTML:
<ul></ul>
JavaScript:
var ul = document.querySelector('ul');
var option = document.createElement('option');
var a = document.createElement('a');
a.innerHTML = "click me";
a.addEventListener('click',function(){
alert('event successful!');
});
option.appendChild(a);
ul.appendChild(option);
See in JSFiddle:
https://jsfiddle.net/63h8kqp1/
You can't add anchor "a" element inside "option", look how this works:
var ul = document.querySelector('ul');
var li = document.createElement('li');
li.innerHTML = "<a href='javascript:alert(\"clicked\")'>click me</a>";
ul.appendChild(li);
<ul></ul>

JavaScript Not able to set focus to first li element within ul

I have below code:
<ul id='someId'>
<li class='someClass'>
</li>
</ul>
I want to set focus on first li element within ul based on some condition.
My first attempt is like this:
var ul = document.getElementById('someId');
var child = ul.childNodes[0];
child.focus();
My second attempt is like this :
var y = document.getElementsByClassName('someClass');
var aNode = y[0];
aNode.focus();
But none of the above works
Any ideas?
The problem is that you can't focus a non input element without setting tabIndex.
<li tabIndex="-1">...</li>
You can Try this fiddle: jsfiddle
An 'li' can't have focus, however an 'input' can, so you write yourself the following script:
function installLI(obj){
var ul = document.createElement('ul');
obj.appendChild(ul);
var li = document.createElement('li');
var txt = document.createElement('input');
li.appendChild(txt);
ul.appendChild(li);
txt.focus();
li.removeChild(txt);
}
Where 'obj' is the object (like an editable div) that you're appending your list to.

Categories

Resources