Adding item to dynamic list - javascript

I'm trying to add text items from the user to a dynamic list. I tried but not getting it. How to go about it...thanks.
<div id="displayList"></div>
Add Text
<script>
var displayList = document.getElementById('displayList')
var inputTxt = document.getElementById('inpText')
var listArray = ['Orange', 'White', 'Green'];
var li;
var ul = document.createElement('ul')
var len = listArray.length;
for(var i=0; i<len; i++){
li = document.createElement('li')
li.appendChild(document.createTextNode(listArray[i]))
ul.appendChild(li)
}
displayList.appendChild(ul)
</script>

The code seems to work just fine as you can see.
var displayList = document.getElementById('displayList')
var inputTxt = document.getElementById('inpText')
var listArray = ['Orange', 'White', 'Green'];
var li;
var ul = document.createElement('ul')
var len = listArray.length;
for(var i=0; i<len; i++){
li = document.createElement('li')
li.appendChild(document.createTextNode(listArray[i]))
ul.appendChild(li)
}
displayList.appendChild(ul)
<div id="displayList"></div>
So the only problem that might exist is if the script is run before the DOM is ready and thus the document.getElementById('displayList') does not return anything because the displayList does not yet exist.
Try running your script at the end of the file. Or run it after the DOM ready event (in the DOMContentLoaded event)
document.addEventListener('DOMContentLoaded', function() {
var displayList = document.getElementById('displayList')
var inputTxt = document.getElementById('inpText')
var listArray = ['Orange', 'White', 'Green'];
var li;
var ul = document.createElement('ul')
var len = listArray.length;
for(var i=0; i<len; i++){
li = document.createElement('li')
li.appendChild(document.createTextNode(listArray[i]))
ul.appendChild(li)
}
displayList.appendChild(ul)
}, false);

Try this:
$('#displayList').append(ul);

Related

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>

Delete unordered list in HTML with Javascript DOM

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';

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