how to store values of visible li elements in javascript? - javascript

I am creating a list of inputs and storing the values in an array when the add button is clicked.
All works well, but I have introduced the possibility to remove items in the list effectively by hiding the 'deleted' elements from the DOM.
Now I need to remove the hidden elements from the array.
To keep things simple, I thought to store in the array only the visible elements (instead of removing the hidden element from the array).
To do so I am looking at adapting the 'how to count visible elements' code in: (https://stackoverflow.com/questions/37634146/javascript-count-visible-elements but it doesn't work and a list of '[object HTMLLIElement]' is displayed when displaying the array on an alert.
This is my code:
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
};
}
// Create a new list item when clicking on the "Add" button
function addNumber() {
var li = document.createElement("li");
var inputValue = document.getElementById("number").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === "") {
alert("Add at least one phone number!");
} else {
document.getElementById("myUL").appendChild(li);
}
// remove elements from form after added to list
document.getElementById("number").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
// without this, the element is not deleted
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
};
}
}
// store values after submit
function submitRecords() {
divs = document.getElementsByTagName("li");
var divsArray = [].slice.call(divs);
var displayShow = divsArray.filter(function (el) {
return getComputedStyle(el).display !== "none";
});
alert(displayShow);
}
#myUL {
/* text-align: center; */
width: 40%;
float: left;
}
/* Style the list items */
ul li {
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #eee;
border-top: lightgrey 1px solid;
border-bottom: lightgrey 1px solid;
font-size: 20px;
transition: 0.2s;
/* this allows for the borders of 2 adiacent items to overlap */
margin-top: -1px;
}
/* Style the close button */
.close {
cursor: pointer;
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: red;
color: white;
}
.addBtn {
background: #eee;
border: black 1px solid;
padding: 4px;
color: black;
cursor: pointer;
}
.addBtn:hover {
background-color: #ddd;
}
<div class="inputForm">
<form>
<input
type="text"
id="number"
placeholder="Enter number"
onkeypress="return isNumberKey(event)"
/>
<span onclick="addNumber()" class="addBtn">Add</span>
<br /><br />
<input
onclick="submitRecords()"
id="send"
type="submit"
value="SEND"
/>
</form>
</div>
<!-- this is needed to generate the list of numbers -->
<ul id="myUL"></ul>
What am I doing wrong?

There is a .value in function addNumber which seems to be spurious, on this line:
divs = document.getElementsByTagName("li").value;
when this is removed the console.log shows li elements.
The code for adding onclick functionality to the span elements looks as though it is trying to step through a (non-existent?) array, and it is doing this each time a number is added. Removing this code and instead setting up the onclick as a span element is created seems to work.
Here is the altered code:
<!-- Added HTML for testing -->
<input id="number" value=999 onchange="addNumber();"/>
<button onclick="submitRecords();">submit records</button>
<ul id="myUL"></ul>
<script>
function submitRecords() {
var divs = (document.getElementsByTagName("li"));// REMOVED .value
var divsArray = [].slice.call(divs);
var displayShow = divsArray.filter(function (el) {
return getComputedStyle(el).display !== "none";
});
var numbers=[];
var keys = [];
for (var i=0;i<displayShow.length;i++) {
numbers[i]=displayShow[i].childNodes[0].textContent;
console.log(numbers[i]);
}
}
function addNumber() {
var li = document.createElement("li");
var inputValue = document.getElementById("number").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === "") {
alert("Add at least one phone number!");
} else {
document.getElementById("myUL").appendChild(li);
}
// close button
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.onclick = function () { //ADDED so that an li element's span child gets this onclick function as soon as it is created
var div = this.parentElement;
div.style.display = "none";
};
span.appendChild(txt);
li.appendChild(span);
/* REMOVED // hide element
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
};
*/
}
</script>

Your idea to get only visible items is just fine, and you can do it like this:
function submitRecords() {
const displayShow = [];
//declare array
[...document.querySelectorAll('#myUL li:not([style="display: none;"])')].forEach(element => {
//get all li items and for each of them:
displayShow.push(element.textContent.slice(0, -1))
//push its text Content into array, and also just remove last x (button) character
});
console.clear();
console.log(displayShow);
}
Ps: li element does not have .value, you can red content with: textContent
Just remove onsubmit event from form, and add back onkeypress="return isNumberKey(event)" to input i made modifications just for demonstration:
EXAMPLE:
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
};
}
// Create a new list item when clicking on the "Add" button
function addNumber() {
var li = document.createElement("li");
var inputValue = document.getElementById("number").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === "") {
alert("Add at least one phone number!");
} else {
document.getElementById("myUL").appendChild(li);
}
// remove elements from form after added to list
document.getElementById("number").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
// without this, the element is not deleted
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
};
}
}
// store values after submit
function submitRecords() {
const displayShow = [];
[...document.querySelectorAll('#myUL li:not([style="display: none;"])')].forEach(element => {
displayShow.push(element.textContent.slice(0, -1))
});
console.clear();
console.log(displayShow);
}
#myUL {
/* text-align: center; */
width: 40%;
float: left;
}
/* Style the list items */
ul li {
position: relative;
padding: 12px 8px 12px 40px;
list-style-type: none;
background: #eee;
border-top: lightgrey 1px solid;
border-bottom: lightgrey 1px solid;
font-size: 20px;
transition: 0.2s;
/* this allows for the borders of 2 adiacent items to overlap */
margin-top: -1px;
}
/* Style the close button */
.close {
cursor: pointer;
position: absolute;
right: 0;
top: 0;
padding: 12px 16px 12px 16px;
}
.close:hover {
background-color: red;
color: white;
}
.addBtn {
background: #eee;
border: black 1px solid;
padding: 4px;
color: black;
cursor: pointer;
}
.addBtn:hover {
background-color: #ddd;
}
<div class="inputForm">
<form onsubmit="event.preventDefault();">
<input
type="text"
id="number"
placeholder="Enter number"
/>
<span onclick="addNumber()" class="addBtn">Add</span>
<br /><br />
<input
onclick="submitRecords()"
id="send"
type="submit"
value="SEND"
/>
</form>
</div>
<!-- this is needed to generate the list of numbers -->
<ul id="myUL"></ul>

I made only small modification to your code to get the desired values from the <li> element.
function submitRecords() {
divs = document.getElementsByTagName("li");
var divsArray = [];
var displayShow = Object.values(divs).filter(function (el) {
return getComputedStyle(el).display !== "none";
});
displayShow.forEach(function(item){let ind=item.innerHTML.indexOf('<span');
divsArray.push(item.innerHTML.substr(0,ind))});
alert(divsArray);
}

Related

How do I load all options in a filtered list on page load? Right now, I have to click "show all" to make that happen

I'm working on displaying a list of books, and I have it set up so you can filter by category. That part of my JavaScript works, but I need to make one tweak. Right now, on page load nothing shows up until you click "show all." What do I need to change in my code so everything loads when the page loads? (Hope that makes sense)
My HTML:
<div id="myBtnContainer">
<button class="bookbtn active" onclick="filterSelection('all')">Show all</button>
<button class="bookbtn" onclick="filterSelection('autobiography')">Autobiography</button>
<button class="bookbtn" onclick="filterSelection('poetry')">Poetry</button>
<button class="bookbtn" onclick="filterSelection('fiction')">Fiction</button>
<button class="bookbtn" onclick="filterSelection('children')">Children</button></div>
<!-- Begin the listing of ALL THE BOOKS! -->
<div class="bookcontainer">
<ul class="booklist">
<div class="filterDiv autobiography">
<li>
<a href="books/singlebook.html">
<img src="images/books/hardy_silence.png" alt="" class="img-book" />
<div class="book-title">Book Title<br></div>
<div class="book-author">by Author</div>
</a>
</li>
</div>
CSS:
.bookcontainer {
overflow: hidden;
}
#myBtnContainer {
z-index: 125;
margin-bottom: 1.5rem;
align-self: left;
align-items: left;
text-align: left;
}
.filterDiv {
float: left;
text-align: center;
display: none;
/* Hidden by default */
}
/* The "show" class is added to the filtered elements */
.show {
display: block;
}
/* Style the buttons */
.bookbtn {
border: none;
outline: none;
padding: 12px 16px;
margin-right: 10px;
background-color: #f1f1f1;
cursor: pointer;
}
/* Add a light grey background on mouse-over */
.bookbtn:hover {
background-color: #ddd;
}
/* Add a dark background to the active button */
.bookbtn.active {
background-color: #666;
color: white;
}
and my JavaScript (copied from w3 if I'm being completely honest):
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
// Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
// Show filtered elements
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
if (arr1.indexOf(arr2[i]) == -1) {
element.className += " " + arr2[i];
}
}
}
// Hide elements that are not selected
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i < arr2.length; i++) {
while (arr1.indexOf(arr2[i]) > -1) {
arr1.splice(arr1.indexOf(arr2[i]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("bookbtn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function () {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
Just simply add:
window.onload = () => {
filterSelection('all')
};
So it will trigger it when page loads.

How to prevent adding another SPAN element?

I'm struggling with a to-do app. I want to cross out a LI element and add a span with an x sign. It's easy by toggling class. However, when I "untoggle" the class by clicking again. The "x" remains and when I click on the item again the "x" is duplicated. How can I prevent adding another "x" or make the "x" disappear when the items is "untoggled".
const addButton = document.querySelector("#add");
const input = document.querySelector("input[name='input-item'");
const ul = document.querySelector("ul");
const allItems = document.querySelectorAll("li");
for (let i = 0; i < allItems.length; i++) {
allItems[i].addEventListener("click", myList);
}
function myList() {
let temp = this.classList.toggle("red");
if (temp) {
let span = document.createElement("span");
span.innerHTML = "×";
span.addEventListener("click", function() {
this.parentElement.remove();
});
this.appendChild(span);
} else if (this.classList.contains("red")) {
this.getElementByTagName("span").remove();
}
}
.red {
text-decoration: line-through;
color: red;
}
span {
background-color: white;
padding: 0 0.3rem;
color: black;
margin: 0 0.2rem;
display: inline-block;
}
<div class="container">
<ul>
<li>banana</li>
<li>orange</li>
<li>grapes</li>
</ul>
<input type="text" name="input-item" placeholder="Enter a new item" /><button id="add">Add Item</button>
</div>

'backgroundColor' not working with javascript

I'm creating a tab menu like this:
function clear_selected() //sets all columns color black
{
var parent = document.querySelector("#container")
var items = document.querySelectorAll(".item")
var n = items.length;
for (var i = 0; i < n; i++)
items[i].style.backgroundColor = "";
}
function plus(itself) //adds another column
{
var parent = itself.parentElement;
var n = parent.childElementCount;
clear_selected();
var n = parent.querySelectorAll(".item").length;
var page = document.createElement("button");
page.className = "item";
page.style.backgroundColor = "blue";
page.textContent = "column"
page.onclick = function() {
clear_selected();
this.style.backgroundColor = "blue";
};
var temp = document.createElement("span");
temp.className = "del"
temp.innerHTML = "×"
temp.onclick = function() { //it's suppose to remove a column and color default as blue
document.querySelector("#main_item").style.backgroundColor = "blue" //THIS LINE ISN'T WORKING
this.parentElement.remove();
};
page.appendChild(temp);
parent.insertBefore(page, parent.childNodes[n]);
}
function see(el) {
clear_selected();
el.style.backgroundColor = "blue";
}
#container {
display: flex;
width: 100%;
height: 50px;
text-align: center;
background-color: yellow;
}
.item {
background-color: black;
color: white;
border: none;
outline: none;
cursor: pointer;
margin: 0.1rem;
padding: 0.1rem;
max-width: 100%;
}
.del {
background-color: red;
display: inline-block;
cursor: pointer;
border-radius: 50%;
width: 0.7rem;
margin-left: 2rem;
}
<div id="container">
<button class="item" id="main_item" style="background-color:blue;" onclick="see(this)">default column </button>
<button class="item" onclick="plus(this)">+</button>
</div>
but when I press the 'x' to remove a column, I want the default column to color blue, but the line of code which is suppose to achieve that isn't working
document.querySelector("#main_item").style.backgroundColor = "blue"
Before pressing 'x':
After pressing 'x' on the last column:
What it SHOULD look like:
I've losing sleep over this, can someone PLEASE tell me why isn't it working?
When you click on the "X", both of your onclick handlers are getting called, including the one that runs clear_selected, which sets the background color to "".
You can fix this by using stopPropagation on the event passed into the onclick function for the "x". That will stop the click event from going up the chain to the parent element of the "x".
temp.onclick = function(e) {
document.querySelector("#main_item").style.backgroundColor = "blue"
this.parentElement.remove();
e.stopPropagation();
};

Element is appended but not shown in nextElementSibling

I have this program that can make closables dynamically. When the user clicks on a created closable an input box and a button are displayed in the content of the closable. The user can then input text into the textbox and then press the button. Then the users text will be displayed in the selected closable content.
Everything works, fine, except for when I try to display the users input in the selected closables content.
Here's what's happening:
When the user inputs something in the text box it's append to the closables content:
The text is only displayed in the closable content after I close the selected closable:
Why isn't the users input being displayed in the selected closable after I click the add task button?
Here is my full code:
var currentClosable;
var currentContent;
function selectedColl(){
document.getElementById("inputTaskDiv").style.display = "block";
currentClosable = event.target;
currentContent = currentClosable.nextElementSibling;
var inputTaskDiv = document.getElementById("inputTaskDiv");
currentContent.append(inputTaskDiv);
}
var taskCounter = 0;
function addTask() {
var text = document.getElementById("taskInput").value;
// create a new div element and give it a unique id
var newTask = $("<input type='checkbox'><label>"+ text + "</label><br>");
newTask.id = 'temp' + taskCounter;
taskCounter++
// and give it some content
var newContent = document.createTextNode(text);
$(currentContent).append(newTask); //Why isn't it being displayed??
console.log("appended");
}
var elementCounter = 0;
var elementCounterContent = 0;
var text;
function addElement() {
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = $("<button class='collapsible' onclick='selectedColl()'></button>").text(text);
var newContentOfDiv = $("<div class='content'></div>");
newDiv.id = 'temp' + elementCounter;
newContentOfDiv.id = 'content' + elementCounterContent;
newDiv.classList = "div";
elementCounter++
elementCounterContent++
// and give it some content
var newContent = document.createTextNode(text);
// add the newly created element and its content into the DOM
document.getElementById("input").value = " ";
$("body").append(newDiv, newContentOfDiv);
newDiv.click(function() {
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active, .collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="input" type="text"><button onclick="addElement()">Add</button>
<div id="inputTaskDiv" style="display:none">
<input id="taskInput" type="text"><button onclick="addTask()">Add Task</button>
</div>
The changes made are in CSS and JS.
In CSS you can see which lines are commented on style ".content": max-height and overflow
The change in JS is:
I changed content.style.maxHeight with this content.style.display
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.display === 'block') {
content.style.display = 'none';
} else {
content.style.display = 'block';
}
Example:
var currentClosable;
var currentContent;
function selectedColl() {
document.getElementById("inputTaskDiv").style.display = "block";
currentClosable = event.target;
currentContent = currentClosable.nextElementSibling;
var inputTaskDiv = document.getElementById("inputTaskDiv");
currentContent.append(inputTaskDiv);
}
var taskCounter = 0;
function addTask() {
var text = document.getElementById("taskInput").value;
// create a new div element and give it a unique id
var newTask = $("<input type='checkbox'><label>" + text + "</label><br>");
newTask.id = 'temp' + taskCounter;
taskCounter++
// and give it some content
var newContent = document.createTextNode(text);
$(currentContent).append(newTask); //Why isn't it being displayed??
console.log("appended");
}
var elementCounter = 0;
var elementCounterContent = 0;
var text;
function addElement() {
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = $("<button class='collapsible' onclick='selectedColl()'></button>").text(text);
var newContentOfDiv = $("<div class='content'></div>");
newDiv.id = 'temp' + elementCounter;
newContentOfDiv.id = 'content' + elementCounterContent;
newDiv.classList = "div";
elementCounter++
elementCounterContent++
// and give it some content
var newContent = document.createTextNode(text);
// add the newly created element and its content into the DOM
document.getElementById("input").value = " ";
$("body").append(newDiv, newContentOfDiv);
newDiv.click(function () {
this.classList.toggle("active");
content = this.nextElementSibling;
if (content.style.display === 'block') {
content.style.display = 'none';
} else {
content.style.display = 'block';
}
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}
.active,
.collapsible:hover {
background-color: #555;
}
.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}
.active:after {
content: "\2212";
}
.content {
padding: 0 18px;
/* max-height: 0; */
/* overflow: hidden; */
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input id="input" type="text"><button onclick="addElement()">Add</button>
<div id="inputTaskDiv" style="display:none">
<input id="taskInput" type="text"><button onclick="addTask()">Add Task</button>
</div>

Displaying javascript multidimensional array in different HTML tags

I have this multidimensional array below i'm trying to display the first and last name in the H3 tags, the age in the H4 tags and the person-desc in the P tags and everything inside the tab. I'm not sure the way i am currently displaying the first and last name is the best way to do it. Is there any better / simple way to accomplish this? Any help would be greatly appreciated!
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
var personArr = [];
var person = {["first-Name"]:"John", ["last-Name"]:"Doe", ["age"]:21, ["person-desc"]:"Nice guy currently still studying"};
var person2 = {["first-Name"]:"Paul", ["last-Name"]:"Logan", ["age"]:22, ["person-desc"]:"Hot tempered person in the military"};
var person3 = {["first-Name"]:"Sean", ["last-Name"]:"Kim", ["age"]:32, ["person-desc"]:"Smart guy working as a Doctor"};
var person4 = {["first-Name"]:"Ken", ["last-Name"]:"Chow", ["age"]:12, ["person-desc"]:"Loves travelling works overseas"};
personArr.push(person, person2, person3, person4);
console.log(personArr);
var parent = document.getElementsByClassName('line1')[0].children;
console.log(parent);
var personFlag = 0;
for(var i = 0; i < parent.length; i=i+1){
parent[i].innerHTML += personArr[personFlag]['first-Name'] +' '+ personArr[personFlag]['last-Name'];
personFlag++
}
body {font-family: Arial;}
/* Style the tab */
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
/* Style the buttons inside the tab */
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current tablink class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
.line1{
display:inline-block;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'People')" id="defaultOpen">People</button>
</div>
<div id="People" class="tabcontent">
<div class="line1">
<h3>Name 1 :</h3>
<h3>Name 2 :</h3>
<h3>Name 3 :</h3>
<h3>Name 4 :</h3>
</div>
</div>
</body>
</html>
Generally, and personally speaking, using innerHTML to modify the DOM in the way you're doing is somewhat frowned on. Instead, you'd create a virtual div, or DocumentFragment, and each of the "person" divs to that. Once that's done you can append the parent fragment to the DOM. This prevents additional rerendering and is generally more readable.
With your code, I would replace this part:
var parent = document.getElementsByClassName('line1')[0].children;
console.log(parent);
var personFlag = 0;
for(var i = 0; i < parent.length; i=i+1){
parent[i].innerHTML += personArr[personFlag]['first-Name'] +' '+ personArr[personFlag]['last-Name'];
personFlag++
}
With This:
var parent = document.getElementsByClassName('line1')[0];
var frag = document.createDocumentFragment();
// Iterate through the Person Array
personArr.forEach((person,i) => {
// `person` is the ith member of personArr
var name = document.createElement('h3');
// Update the contents of your h3 element and add it to the fragment.
name.textContent = `Name ${i}: ${person['first-Name']} ${person['last-Name']}`;
frag.appendChild(name);
});
// Add the fragment to the parent :)
parent.appendChild(frag);
A non-es6 version would look like this.
var parent = document.getElementsByClassName('line1')[0];
var frag = document.createDocumentFragment();
// Iterate through the Person Array
for(var i = 0; i < personArr.length; i++) {
var person = personArr[i];
// Create our h3 element, to house the person's name.
var name = document.createElement('h3');
// Update the contents of your h3 element and add it to the fragment.
name.textContent = [
'Name',
i,
':',
person['first-Name'],
person['last-Name']
].join(' ');
frag.appendChild(name);
}
// Add the fragment to the parent :)
parent.appendChild(frag);
Additionally, you would also have to remove all the children from the HTML in order for this to work properly. i.e. make the line1 element look like this:
<div class="line1"> </div>

Categories

Resources