Delete unordered list in HTML with Javascript DOM - javascript

Basically, the task I needed to perform is to delete the whole "agent" array by using the removeChild() function, but it needs the <ul> id, according to what I read [here][1].
After that, I need to replace the "agent" array with "freshagent" array and display it in an unordered list.
My problem is that I can't set the id for "ul" because I used the createElement() function.
Thus, I can't remove the "agent" array.
//old code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
</div>
<script>
var agents = [
"Dion" ,
"Elisa" ,
"Selena" ,
"Shauna" ,
"Rodger"
];
var freshAgents = [
"Gray",
"Shivani",
"Brainne",
"Jason",
"FChad"
];
var i = 0;
var ul = document.createElement('ul');
ul.setAttribute("id","aList");
for (i in agents){
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
rList = document.getElementById("aList");
if (rList.hasChildNodes()){
for(i in agents){
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (i in finalList){
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
document.getElementById("wrapper").appendChild(ul);
</script>
</body>
</html>
//new code(working)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
</div>
<script>
var agents = ["Dion" ,"Elisa" , "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason","FChad"];
var i = 0;
var ul = document.createElement('ul');
for (i in agents){
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
var rList = document.getElementById("wrapper").appendChild(ul);
do{
rList.removeChild(rList.childNodes[0]);
}while(rList.hasChildNodes())
for (i in freshAgents){
var list = document.createElement('li');
list.appendChild(document.createTextNode(freshAgents[i]));
ul.appendChild(list);
}
</script>
</body>
</html>

Seems like you are going about it a really long way. I have tweaked your code somewhat to make it do what I think you are asking. I would do something different but it seems clear from your question that this is the way you want it.
var agents = ["Dion", "Elisa", "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason", "FChad"];
var ul = document.createElement('ul');
ul.id = "aList";// give it an ID
for (var i = 0; i < agents.length; i++) {
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list);
}
document.getElementById("wrapper")
.appendChild(ul);
rList = document.getElementById("aList");//this is the same as ul variable declared above
if (rList.hasChildNodes()) {
console.log(rList.childNodes);//lists the <LI>...<LI> nodes
for (var i = 0; i < rList.childNodes.length; i++) {//Loop through the nodes not your agent array
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (var i = 0; i < finalList.length; i++) {
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
Working fiddle here

I can't really understand much of your question, but based on this
Problem: I can't set id for "ul" because of using createelement function. I can't remove "agent" array.
I assume you want to add an id to an element that was created with document.createElement(). You can do that like so:
var el = document.createElement('div');
el.id = 'exampleID';

First of all, please input your code in a neat and legible manner, so that it is readable by everyone. I've formatted your code to the following:
var agents = ["Dion", "Elisa", "Selena", "Shauna", "Rodger"];
var freshAgents = ["Gray", "Shivani", "Brainne", "Jason", "FChad"];
var i = 0;
var ul = document.createElement('ul');
ul.setAttribute("id", "aList");
for (i in agents) {
var list = document.createElement('li');
var node = document.createTextNode(agents[i]);
list.appendChild(node);
ul.appendChild(list); }
rList = document.getElementById("aList");
if (rList.hasChildNodes()) {
for (i in agents) {
rList.removeChild(rList.childNodes[i]);
}
}
var finalList = agents.concat(freshAgents);
for (i in finalList) {
var list = document.createElement('li');
list.appendChild(document.createTextNode(finalList[i]));
ul.appendChild(list);
}
document.getElementById("wrapper").appendChild(ul);
Another tip: since you're referring your HTML, it's recommended that you provide that code as well. Again, it's not a necessity, but just etiquette.
As for setting the id, use:
var example = document.createElement('ul');
example.id = 'example_ID';

Related

How to show firebase query results on html as a list?

I'm developing a js, html & firebase webapp.
I'm trying to get list of scores from firebase and show them on html.
I think my query is working, but I can't show the results on html.
I tried first a code which worked on a video but it did not work for me (https://www.youtube.com/watch?v=NcewaPfFR6Y)
(html)
<p>
<ol id ="scorelist">
</ol>
</p>
(js)
function gotData(data) {
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = createElement('li', score);
li.parent('scorelist');
}
}
I get error createElement is not defined. When I try document.createElement then li.parent('scorelist') does not work and I get error li.parent is not a function.
Then I tried something like this but it did not work out either.
var scorelist = document.querySelector('#scoreslist')
function gotData(data) {
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = document.createElement('li', score);
scorelist = li.textContent;
}
}
I've been really stuck with this one! I would be grateful for some help, thanks!
I added an example with comments that may explain to you what i did.
function gotData() {
// you had typo on the id, make sure you select the correct element.
const scorelist = document.querySelector("#scorelist");
var scores = { first: { score: 1 }, second: { score: 2 } };
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
// first, create the element
const newListItem = document.createElement("li", score);
// and then, set the score as textContent of the newListitem.
newListItem.textContent = score;
// finally you should add the newListItem to the list parent element.
scorelist.appendChild(newListItem);
}
}
If you find problems, there might be input errors, built-in function problems, library api problems, algorithm problems, logic problems, etc. Try to read documents and find solutions for each possible problem.
method 1 Not use JQuery:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
If correct, list values will show below:
<p>
<ol id ="scorelist">
</ol>
</p>
</div>
<script>
function gotData() {
var scorelist = document.querySelector("#scorelist");
var scores = { first: { score: 660 }, second: { score: 330 } };
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var score = scores[k].score;
var li = document.createElement("li");
li.innerHTML = score;
scorelist.appendChild(li);
}
}
//call the function
gotData();
</script>
<br>
<br>
The rest of the body
</body>
</html>
method 2 JQuery:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<div>
If correct, list values will show below:
<p>
<ol id ="scorelist">
</ol>
</p>
</div>
<script>
function gotData() {
var scorelist = $("#scorelist");
var scores = '{ "first": { "score": 660 }, "second": { "score": 330 } }';
var objkeys = $.parseJSON(scores);
$.each(objkeys, function( key, value ) {
$.each(value, function(key, value){
li = $("<li/>");
li.css("color", "blue").text(value).appendTo(scorelist);
});
});
}
//call the function
gotData();
</script>
<br>
<br>
The rest of the body
</body>
</html>
Docs: createElement 1 2,
querySelector,
Object.keys 1 2,
selector, append, parent.
Also search your errors in stackoverflow. say get error createElement is not defined. see articles like jquery-document-createelement-equivalent, creating-a-div-element-in-jquery. And test result in websites, like jsfiddle

Card from Javascript into HTML, there must be a better way (working)

There must be a better, shorter way to generate many cards from javascript into HTML.
This is the format to follow, it's working but can it be better?????
span{color: red;}
<div id="mycard"></div>
var dateSpan = document.createElement('span')
var ul = document.createElement('ul')
var ol = document.createElement('ol')
var li = document.createElement('li');
var li2 = document.createElement('li')
dateSpan.innerHTML = '#3500';
li.textContent = 'Title of card '
li2.textContent = '"Small description"'
li.appendChild(dateSpan);
li.appendChild(ul);
ul.appendChild(li2);
ol.appendChild(li);
var app = document.querySelector('#mycard');
app.appendChild(ol)
Note: Yeah, you can add a '<b/r>' but the "Small description" should be stylish later on... :)
Create a function to generate html content and then call that function as many time as you want.
For example
function generateList(title, description){
var htmlVal = `<li>${title}<br>${description}</li>`;
return htmlVal;
}
Then call the function however you like and append it to the element.
document.getElementById("myCard") += generateList("Title of Card #3500","Small description");
Where in your html there's an element with id "myCard"
You can create a class cardMaker and create instances with a for loop:
class cardMaker {
constructor(n) {
var dateSpan = document.createElement('span')
var ul = document.createElement('ul')
var ol = document.createElement('ol')
var li = document.createElement('li');
var li2 = document.createElement('li')
dateSpan.innerHTML = '#3500' + n;
li.textContent = 'Title of card '
li2.textContent = '"Small description"'
li.appendChild(dateSpan);
li.appendChild(ul);
ul.appendChild(li2);
ol.appendChild(li);
var app = document.querySelector('#mycard');
app.appendChild(ol)
}
}
let cards = [];
for (let i = 0; i < 10; i++) {
cards[i] = new cardMaker(i);
}

create element and then insert html tag

I have a json data and I'm looping inside of it and create a set of li's in every (.searchinput-sub)
var searchinput_sub = document.querySelectorAll(".searchinput-sub");
for (var i = 0, max = searchinput_sub.length; i < max; i++) {
var jsonResData = JSON.parse(e.data);
for(var l=0;l<jsonResData.length;l++){
//create a li element
var newEl = document.createElement('li');
newEl.innerHtml ='test';
searchinput_sub[i].querySelector('.resultsHolder').appendChild(newEl);
}
}
but this part
newEl.innerHtml ='test';
is not working, like only li tags was added. Any ideas, help please?
It will be innerHTML not innerHtml:
newEl.innerHTML ='test';

how to create new list and add list items to new list using javascript

I am trying to create a new list and add it to the DOM, and then add list items to new list along with text node to each list item.
This is what I have so far, after trying several ways to do this, but still not accomplishing goal. any help is appreciated.The first 4 lines of code is HTML snippet, the code below that is the JavaScript code. Again thank you for any help with this.
<body>
<div id="nav"></div>
<script src="js/script.js"></script>
</body>
var newList = document.createElement("ul");
var newListItem = document.createElement("li");
var stringArray = ["Home","About","Our Services","Contact Us"];
var newUL = document.getElementById("nav").appendChild(newList);
function buildList(){
for( var i = 0; i < stringArray.length; i++){
newUL.appendChild(newListItem);
}
var listItems = document.getElementsByTagName("li");
for( var i = 0; i < listItems.length; i++){
listItems[i].appendChild(stringArray[i]);
}
}
buildList();
Two problems:
You're appending the same li over and over. You need to create a new one for each item.
You can't append a string to a DOM element, but you can set its textContent:
var stringArray = ["Home","About","Our Services","Contact Us"];
function buildList(){
var newList = document.createElement("ul");
var newListItem;
document.getElementById("nav").appendChild(newList);
for( var i = 0; i < stringArray.length; i++){
newListItem = document.createElement('li');
newListItem.textContent = stringArray[i];
newList.appendChild(newListItem);
}
}
buildList();
<div id="nav"></div>
Slightly cleaner version with .forEach():
var stringArray = ["Home","About","Our Services","Contact Us"];
function buildList(){
var newList = document.createElement("ul");
document.getElementById("nav").appendChild(newList);
stringArray.forEach(function (title) {
var newListItem = document.createElement('li');
newListItem.textContent = title;
newList.appendChild(newListItem);
});
}
buildList();
<div id="nav"></div>
You need to create a text node and append it to the <li> element.
var newList = document.createElement("ul");
var stringArray = ["Home","About","Our Services","Contact Us"];
// Create a <ul> element
var newUL = document.getElementById("nav").appendChild(newList);
function buildList(){
for(var i = 0; i < stringArray.length; i++){
// Create a text node
var newTextNode = document.createTextNode(stringArray[i]);
// Create a list element
var newListItem = document.createElement("li");
// Append text node and list item
newListItem.appendChild(newTextNode);
newUL.appendChild(newListItem);
}
}
buildList();
<body>
<div id="nav"></div>
</body>
Just loop over the string array and add lis, like this:
var nav = document.querySelector("nav");
var list = document.createElement("ul");
var items = ["Home","About","Our Services","Contact Us"];
items.forEach(function(item) {
var li = document.createElement("li");
li.innerText = item;
list.appendChild(li);
})
nav.appendChild(list);
Codepen example here
If it's supposed to be a site navigation, you may want to add links. That's easy, too – just append <a> in the loop like this:
var nav = document.querySelector("nav");
var list = document.createElement("ul");
var items = [{
text: "Home",
url: "/home"
}, {
text: "About",
url: "/about"
}, {
text: "Our services",
url: "/services"
}, {
text: "Contact Us",
url: "/contact"
}]
items.forEach(function(item) {
var li = document.createElement("li");
var link = document.createElement("a");
link.innerText = item.text;
link.href = item.url;
li.appendChild(link);
list.appendChild(li);
})
nav.appendChild(list);
Codepen example here
In this case, I would contend that using innerHTML and Array#join is simpler and more readable than other alternatives:
var stringArray = ["Home", "About", "Our Services", "Contact Us"];
function buildList() {
document.getElementById('nav').innerHTML = '<ul><li>' + stringArray.join('</li><li>') + '</li></ul>'
}
buildList()
<nav id="nav"></nav>

Adding class to elements in a loop processing AJAX response

AJAX request returns XML containing such nodes:
<root>
<directory><li onclick=myFunc()>stuff</li></directory>
...
</root>
Then code processes it like this:
var folderContent = '';
var data = xhttp.responseXML;
var folders = data.getElementsByTagName("directory");
for (var i = 0; i < folders.length; i++) {
folderContent += folders[i].childNodes[0].nodeValue;
}
document.getElementById('folders').innerHTML = folderContent;
I want to add to every list item one class (identical to every element). How should I do that using JavaScript?
Thanks.
You can use setAttribute to set add(or change) an attribute. Also I notice you are calling nodeValue on an element node which is always undefined.
If your aim is to append the li node to folderContent then you will have to serialize it to string before appending to folderContent.
var folderContent = '';
var data = xhttp.responseXML;
var folders = data.getElementsByTagName("directory");
var serializer = new XMLSerializer();
var node;
for (var i = 0; i < folders.length; i++) {
node=folders[i].childNodes[0];
node.setAttribute('class', 'your-class')//sets class attribute to li node
folderContent += serializer.serializeToString(node);//serialize li node before and appends it to folderContent
}
Hope it helps.
It worked:
var ul = document.createElement('ul');
var li;
for (var i = 0; i < folders.length; i++) {
li = document.createElement('li');
li.innerHTML = folders[i].childNodes[0].nodeValue;
li.setAttribute('onclick', 'Toggle(this, true)');
li.setAttribute('class', 'first-level');
ul.appendChild(li);
}
document.getElementById('folders').innerHTML = ul.innerHTML;

Categories

Resources