How can i make the loops and create it dynamically? - javascript

How to correct the javascript code to create li dynamically
to make loops?
I use this code, how to do it?
Because in this code I have to repeat for each section
let content = document.createElement('span');
let liststart = document.createElement('span');
let listelement1 = document.createElement('li');
let listelement2 = document.createElement('li');
let listelement3 = document.createElement('li');
let listelement4 = document.createElement('li');
listelement1.innerHTML = "section 1";
listelement2.innerHTML = "section 2";
listelement3.innerHTML = "section 3";
listelement4.innerHTML = "section 4";
let section1 = document.getElementById("section1");
let section2 = document.getElementById("section2");
let section3 = document.getElementById("section3");
let section4 = document.getElementById("section4");
listelement1.addEventListener("click", function() {
section1.scrollIntoView(true);
section1.classList.add("my-active");
section2.classList.remove("my-active");
section3.classList.remove("my-active");
section4.classList.remove("my-active");
});
listelement2.addEventListener("click", function() {
section2.scrollIntoView(true);
section1.classList.remove("my-active");
section2.classList.add("my-active");
section3.classList.remove("my-active");
section4.classList.remove("my-active");
});
listelement3.addEventListener("click", function() {
section3.scrollIntoView(true);
section1.classList.remove("my-active");
section2.classList.remove("my-active");
section3.classList.add("my-active");
section4.classList.remove("my-active");
});
listelement4.addEventListener("click", function() {
section4.scrollIntoView(true);
section1.classList.remove("my-active");
section2.classList.remove("my-active");
section3.classList.remove("my-active");
section4.classList.add("my-active");
});
liststart.appendChild(listelement1);
liststart.appendChild(listelement2);
liststart.appendChild(listelement3);
liststart.appendChild(listelement4);
content.appendChild(liststart);
let navbar__list = document.querySelector('#navbar__list');
navbar__list.append(content);
let tabs = document.getElementsByTagName("li");
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function() {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active");
this.className += "active";
});
}

Hopefully this will work as an example for you:
let content = document.createElement('span');
let liststart = document.createElement('span');
var sections = [];
for(let i = 1; i <= 4; i++) {
const listElement = document.createElement('li');
listElement.innerText = `Section ${i}`
const section = document.getElementById(`section${i}`)
sections.push(section)
listElement.addEventListener("click", () => {
section.scrollIntoView(true)
sections.forEach(el => el.classList.remove("my-active"))
section.classList.add("my-active")
})
liststart.appendChild(listElement)
}
content.appendChild(liststart);
let navbar__list = document.querySelector('#navbar__list');
navbar__list.append(content);
let tabs = document.getElementsByTagName("li");
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function() {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active");
this.className += "active";
});
}
If I was to do this myself, knowing there were an "unknown" number of sections, I would use JavaScript code that used every section whose id started with "secton":
let content = document.createElement('span');
let liststart = document.createElement('span');
// this line puts all elements that have an id starting with 'section' into an array
var sections = [...document.querySelectorAll('[id^=section]')]
sections.forEach(section => {
const listElement = document.createElement('li');
listelement.innerText = `Section ${i}`
listElement.addEventListener("click", () => {
section.scrollIntoView(true)
sections.forEach(el => el.classList.remove("my-active"))
section.classList.add("my-active")
})
liststart.appendChild(listElement)
})
content.appendChild(liststart);
let navbar__list = document.querySelector('#navbar__list');
navbar__list.append(content);
let tabs = document.getElementsByTagName("li");
for (let i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function() {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active");
this.className += "active";
});
}
This solution is quite similar, but to me is a bit more readable.

Related

Having issues creating a for loop for a list created in JS

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
var helloWorld = document.getElementById("OLJS");
for (var i = 0; headOne < 10; i++){
var listItems = document.createElement("li");
listItems.innerHTML = headOne[i];
helloWorld.append(listItems);
}
If you want to loop 10 times then do:
for (let i = 0; i < 10; i++) {
// Do something
}
And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:
for (let i = 0; i < headOne.textContent.length; i++) {
let listItems = document.createElement('li')
listItems.textContent = headOne.textContent[i]
helloWorld.append(listItems)
}
You might also want to read more about Loops and iteration
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
//var helloWorld = document.getElementById("OLJS");
for (var i = 0; i < 10; i++) {
var listItems = document.createElement("li");
listItems.innerHTML = "order list item " + (i + 1);
newOrderedList.append(listItems);
}

Update Array when new elements are displayed on webpage

I'm working on a chrome extension where I need to gather the total number of books in a library.
The code below works fine, however, the page where I'm getting the data only loads half of the books at once until you scroll down further and the array doesn't update accordingly.
Is there a way to automatically update the array to keep up with the changes?
let list = document.querySelectorAll("ul > li");
let numBooks = [];
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
console.log(numBooks);
// Variables
let list = document.querySelectorAll("ul > li");
let mlist = document.querySelector("ul");
let numBooks = [];
// Push books to array
for (let i = 0; i < list.length; i++) {
numBooks.push(i + 1);
}
// Observe changes
const observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.addedNodes.length) {
// Create Element: Book Count
let url = "myurl";
let nBooks = numBooks.length / 10;
let nChanges = mutation.addedNodes.length - 1;
if (url == window.location.href) {
let el = document.createElement("span");
el.innerHTML = nBooks + nChanges;
let par = document.getElementsByTagName("h2")[0];
par.appendChild(el);
}
}
});
});
observer.observe(mlist, {
childList: true,
});

appendChild to the side or right

I am using appendChild to show new sets of div but it is just added below. Is there a way to get it to the right or left side?
for (i = 0; i <= data.length; i++) {
let courseName = data[i].name;
let courseid = data[i]._id;
let desc = data[i].description;
let isActive = data[i].isActive;
let id = document.getElementById("divHolder");
let newDiv = document.createElement("div")
if (isActive === true) {
isActive = 'Active'
} else {
isActive = 'Inactive'
}
newDiv.innerHTML = `<div>this content to append</div>`
id.prepend(newDiv);
}
Give your div an id using Element.setAttribute, and then move it to the left or right using CSS.
for (i = 0; i <= data.length; i++) {
let courseName = data[i].name;
let courseid = data[i]._id;
let desc = data[i].description;
let isActive = data[i].isActive ? "Active" : "Inactive";
let container = document.getElementById("divHolder");
let newDiv = document.createElement("div");
newDiv.setAttribute("id", "new-div");
newDiv.innerHTML = `<div>this content to append</div>`
container.prepend(newDiv);
}
#new-div {
float: right;
}

Is this javasScript sorting function correct?

I'm a javaScript begginer. This function works and allows me to sorting list by ascendant and descendant by clicking in a button but I would like to know if it's properly written or maybe it can be simplified or written differently. Thanks in advance.
index.html
<p id="sort">Sort</p>
<ul>
<li>Phosphorus</li>
<li>Polonium</li>
<li>Radium</li>
<li>Fluorine</li>
<li>Iron</li>
<li>Hydrogen</li>
<li>Germanium</li>
<li>Mercury</li>
<li>Actinium</li>
<li>Barium</li>
<li>Calcium</li>
<li>Cadmium</li>
</ul>
<script src="main.js"></script>
main.js
const sortButton = document.querySelector("#sort");
let counter = 0;
eventListeners();
function eventListeners() {
sortButton.addEventListener("click", sortList);
}
function sortList() {
const elementsList = new Array();
const elements = document.querySelectorAll("ul li");
for (const element of elements) {
elementsList.push(element.textContent);
}
const ul = document.querySelector("ul");
ul.innerHTML = "";
if (counter % 2 === 0) {
const orderedList = elementsList.sort();
for (let i = 0; i < orderedList.length; i++) {
const li = document.createElement("li");
li.innerHTML = orderedList[i];
ul.appendChild(li);
}
counter++;
} else {
const orderedList = elementsList.reverse();
for (let i = 0; i < orderedList.length; i++) {
const li = document.createElement("li");
li.innerHTML = orderedList[i];
ul.appendChild(li);
}
counter++;
}
}
you don't have to clear the innerHTML of the ul, nor even ever use innerHTML
element.appendChild will move existing elements - as below
const sortButton = document.querySelector("#sort");
let counter = 0;
eventListeners();
function eventListeners() {
sortButton.addEventListener("click", sortList);
}
function sortList() {
const elementsList = Array.from(document.querySelectorAll("ul li"));
const ul = document.querySelector("ul");
elementsList.sort(({textContent:a}, {textContent:b})=>(counter%2?-1:1)*a.localeCompare(b))
.forEach(el => ul.appendChild(el));
counter++;
}
<p id="sort">Sort</p>
<ul>
<li>Phosphorus</li>
<li>Polonium</li>
<li>Radium</li>
<li>Fluorine</li>
<li>Iron</li>
<li>Hydrogen</li>
<li>Germanium</li>
<li>Mercury</li>
<li>Actinium</li>
<li>Barium</li>
<li>Calcium</li>
<li>Cadmium</li>
</ul>
In Es2015 (i.e. old school javascirpt) - this function looks like:
function sortList() {
var elementsList = Array.from(document.querySelectorAll("ul li"));
var ul = document.querySelector("ul");
elementsList.sort(function (_ref, _ref2) {
var a = _ref.textContent;
var b = _ref2.textContent;
return (counter % 2 ? -1 : 1) * a.localeCompare(b);
}).forEach(function (el) {
return ul.appendChild(el);
});
counter++;
}

Cannot read property 'classList' of undefined when using it for DIVs

Me again. I modified the code a bit but
I have an error.
Cannot read property 'classList' of undefined. It happens at:
slides[this.current].classList.remove("visible");
const innerDiv1 = document.createElement("div");
innerDiv1.id = "innerDivID1";
//innerDiv1.classList.add("innerDivClass");
innerDiv1.classList.add("visible");
innerDiv1.innerText = "1";
const innerDiv2 = document.createElement("div");
innerDiv2.id = "innerDivID2";
innerDiv2.classList.add("innerDivClass");
//innerDiv2.classList.add("visible");
innerDiv2.innerText = "2";
const innerDiv3 = document.createElement("div");
innerDiv3.id = "innerDivID3";
innerDiv3.classList.add("innerDivClass");
//innerDiv3.classList.add("visible");
innerDiv3.innerText = "3";
rightButton() {
let next = document.getElementById("next");
next.addEventListener("click", () => {
this.nextSlide();
});
}
nextSlide() {
const slides = document.querySelectorAll(
"#outsideCaroussel, .innerDivClass"
);
for (let i = 0; i <= slides.length; i++) {
if ((slides.className = "visible")) {
slides[this.current].classList.remove("visible");
slides[this.current].classList.add("innerDivClass");
}
if ((slides.className = "innerDivClass")) {
slides[this.current].classList.add("visible");
slides[this.current].classList.remove("innerDivClass");
}
this.current++;
console.log(slides);
console.log(this.current);
}
Note.
this.current = 0 {at the beginning of the code, the index of the current shown div}
On your code this.current will go outside your sliders divs in this case you have to use the index i
nextSlide() {
const slides = document.querySelectorAll(
"#outsideCaroussel, .innerDivClass"
);
// It should check less than slides.length, on equality slides[i] would be exceeding bound
for (let i = 0; i < slides.length; i++) {
if ((slides.className = "visible")) {
slides[i].classList.remove("visible");
slides[i].classList.add("innerDivClass");
}
if ((slides.className = "innerDivClass")) {
slides[i].classList.add("visible");
slides[i].classList.remove("innerDivClass");
}
}
}

Categories

Resources