For loop only loops 1 time - JavaScript - javascript

Hi i am trying to make a for loop which will automatically add "dots" depending on how many images there are, i use the myArrImg.length but it only outputs a li with a class of dots once even tho it should do it four times? can anyone help me :)
var myArrImg = ['img/erftdgdf33.jpg','img/iajdi89.jpg','img/isdkfj01.jpg','img/wergf43.jpg'];
function dotsAuto(){
var test = document.getElementById('test');
var li = document.createElement('li');
li.className = 'dots';
for (i = 0; i < myArrImg.length; i++) {
test.appendChild(li);
}
}
dotsAuto();

Your problem is not what you think. The loop is operating the right number of times, but it is not doing what you intend.
The problem is that you only ever create one li element. You then repeatedly insert that same element. So the browser thinks you are doing this:
Create an li element. Give it a className. Now, start looping through the myArrImg array. On the first time, insert that li element. On the second time, insert that li element. On the third time, insert that li element. And so on.
You need to create new li elements each time, because any element can only exist once in the document. Essentially, you keep removing the element from the document and putting it back in the same place To create new elements each time, create the li within the loop:
var li;
for (i = 0; i < myArrImg.length; i++) {
li = document.createElement('li');
li.className = 'dots';
test.appendChild(li);
}

Here I created an ul since JSFiddle doesn't allow to manipulate document, but the process is the same
var myArrImg = ['img/erftdgdf33.jpg','img/iajdi89.jpg','img/isdkfj01.jpg','img/wergf43.jpg'];
function dotsAuto(){
var test = document.getElementById('test');
for (i = 0; i < myArrImg.length; i++) {
var li = document.createElement('li');
li.className = 'dots';
li.innerHTML = myArrImg[i];
test.appendChild(li);
}
}
dotsAuto();
<ul id="test">
</ul>
Basically you create ONE li for EACH loop cycle, and then append it to the list

Related

How to separate Li items when selecting multiple options in a variable product?

I am creating a feature on a Woocommerce variable product page where a user can select an option and that option gets added to a summary of items selected. I have multiple variations on the page so I have tried to get the innerHTML of every selected target and tried to add it to the UL by dynamically creating an li and adding to it. But at the moment only one li gets created and it adds all the options selected to it. Is there a way to separate each variation into multiple li's so that it adds the selected option to its own individual li? This is what I have so far.example here. It would be greatly appreciated if I am pointed in the right direction. Thanks a lot :)
var wrappers = document.querySelectorAll('.rtwpvs-terms-wrapper');
var summary = document.querySelector('.selection-summary');
var list = document.querySelector('.selected-items');
var li = document.createElement("li");
wrappers[0].classList.remove('opacity');
let increment = 0;
wrappers.forEach((item, sel) => {
item.addEventListener('click', (e) => {
summary.style.display = 'block';
// Create li items and assign on click innerhtml
li.appendChild(document.createTextNode(e.target.innerHTML));
list.appendChild(li);
increment++;
for(var i = 0; i < wrappers.length; i++) {
wrappers[increment].classList.remove('opacity');
}
})
})
You're appending to the same li (which you created at the top level) at every iteration of your loop. You should be creating a new <li> for each item, and append said <li> to your list, like so:
// Create li items and assign on click innerhtml
const li = document.createElement("li");
li.innerHTML = e.target.innerHTML;
list.appendChild(li);
You don't need the var li = document.createElement("li"); at the top level anymore.

dynamically created id in javascript

I need loop in Javascript - when You click on button it add ol tu ul and gave id with number, like this:
<ol id="single-task1"></ol>
<ol id="single-task2></ol>
And so on...
When I tried whit loop like this:
taskNumber = 0;
for (var i; i<999; i++){
taskNumber++;
}
var ol = document.createElement('ol'); //creating element ol
taskValue = textField.value; //getting value from user
taskList.appendChild(ol); //add ol to ul
ol.id = 'single-task-'+taskNumber;
ol.innerHTML = taskValue; //add value from user to new ol
All ol elements still have "single-task-0"... Probably loop is in wrong place or loop is wrong.
You are confusing your taskNumber and your i variable. Initialize i = 0 in your loop and use that. Do all of your work within the loop. You don't need taskNumber.

How can i replace HTML tag to another in javascript

I am new with js and playing with replace method.
I have had no problems when replacing string for another string etc., but when im trying to do same with tags nothing happens..
Im trying to replace every tags for -tags. My function is below:
function bonus() {
var list = document.getElementsByTagName('li');
for (var i = 0; i < list.length; i++) {
newList = document.getElementsByTagName('li')[i].innerHTML;
newList = newList.replace('<li>', '<strong>');
newList = newList.replace('</li>', '</strong>');
document.getElementsByTagName('li')[i].innerHTML = (newList);
//console.log(newList);
}
}
function bonus(){
var list=document.getElementsByTagName('li');
var len = list.length;
for(var i=len-1; i>-1; i--){
var tmpItem = list[i]
newList = tmpItem.outerHTML;
newList = newList.replace('<li>','<strong>');
newList = newList.replace('</li>','</strong>');
tmpItem.outerHTML = newList;
}
}
I thought you might change your code like above, and there was still much space to optimize your code. go ahead <( ̄︶ ̄)>
First of all you should never replace a list-item with another element like that. A list item must always be a child of an ul or ol elelment, and ul and ol elements should not have any other immediate child that isn't a li.
However, this doesn't work because the li is an html element and not a text string and the inner HTML of an html elemnt doesn't contain the tag itself. It may contain children and those children's tags are part of the innerHTML, everything inside the element/tag itself is the innerHTML.
An example to clarify:
<ul>
<li>one<strong>second one</strong></li>
<li>two<strong>second two</strong></li>
<li>three<strong>second three</strong></li>
<li>four</li>
</ul>
Looping through all list items accessing elements as you've describe
for(var i=0; i<list.length;i++) {
console.log("==>> " + document.getElementsByTagName("li")[i].innerHTML);
}
Will output the following to the console:
==>> one<strong>second one</strong>
==>> two<strong>second two</strong>
==>> three<strong>second three</strong>
==>> four
If you want to make all li elements strong they should be nested as this:
<li><strong>Some text</strong></li>
To Achieve this one way to do it would be:
var list = document.getElementsByTagName("li");
for(var i=0; i<list.length; i++) {
var listItem = list[i];
listItem.innerHTML = "<strong>" + listItem.innerHTML + "</strong>";
}
If you want to convert all li elements to strong elements you must first remove them from the list...
Thanks alot for all of you. I knew that i can't change li for strong in real world, but i just tried to figure out if its possible to do so with simple loop.
My example html is full of lists, so thats why i used li instead of h2 to h3 or something like that. Outer html was new thing for me, and solution for this one. However Kim Annikas answer helped me with other question about modifying lists: I did this:
function replace(){
var list=document.getElementsByTagName('li');
for(var i=0;i<list.length;i++){
newText="<strong>Replaced!</strong>";
var listItem=list[i];
listItem.style.color="red";
listItem.innerHTML=newText;
}
}
..and now it seems that i have learnt how to modify tags as well as text inside of it ;)

Create elements only once inside for loop and assign id to it from an array using jquery

I have an array majorArray, suppose it contains 20, 25, 30, 35. When I put it inside a loop and create elements dynamically as coded below, this element is created multiple times as the length of an array. However, I only want to create only one for each value and assign id by value of a specific position of an array to the li tag.
Please help to solve my problem?
for(i = 0; i <= majorArray.length; i++) {
var ul_client_listing = ('.clientlisting').addClass('client_ul').append('<ul>');
var li_client_listing = $('.client_ul ul').addClass('client_li').append('<li id="first'+majorArray[i]+'" class="mainli"> <div class="cientname"> </div></li>');
$('.cientname').append('<input type="text" placeholder="comment..." class="reviewtext1" style="margin-top:10px"/>');
}
The problem with the way you're creating and adding new elements is you use selectors which not only selects the newly created elements, but all such elements.
For example inside your loop you have:
var ul_client_listing = ('.clientlisting').addClass('client_ul').append('<ul>');
And then right after that you append a li to $('.client_ul ul') which is not only the newly created ul, but all the ul with an ancestor with class .client_ul. And the same about li elements.
You can do it like this:
var container = $('.clientlisting').addClass('client_ul');
for (i = 0; i <= majorArray.length; i++) {
var ul = $('<ul/>');
var li = $('<li/>').prop('id', 'first' + majorArray[i]).addClass('mainli');
var div = $('<div/>').addClass('cientname');
var inp = $('<input/>').attr({
type: 'text',
placeholder: 'comment...',
class: 'reviewtext1'
}).css('margin-top', '10px');
div.append(inp);
li.append(div);
ul.append(li);
container.append(ul);
}

Parse header to unordered list IN PLAIN JS

A part of my script
function lab()
{
var h1 = getElementsByTagName("H1");
var li = document.createElement("LI");
var ul = document.createElement("UL");
li.innerHTML = h1.innerHTML;
h1[0].parentNode.replaceChild(ul,h1[0]);
h1[0].parentNode.appendChild(li);
}
doesn't do anything.
The whole task is to change a combination of headers to unordered list using only plain js with DOM. There has already been a question here but unfortunately the solution provided there was in jQuery, not in plain JS.
Could you please give me a hint?
I'm not sure what exactly you need, perhaps something like this:
function lab() {
var h1 = document.getElementsByTagName('h1'), // Create a collection of H1 elements
ul = document.createElement('ul'), // Create a new UL element
parent = h1[0].parentNode, // Store the parent node of the first H1
n, len, li; // Declare some variables to use later
for (n = 0, len = h1.length; n < len; n++) { // Iterate through H1 elements
li = document.createElement('li'); // Create a new LI element
li.appendChild(h1[0]); // Move a H1 to LI (Live collection, 0 instead of n as index)
// Or switch the line above to the next two lines, if you want to remove the H1 and list the content only
// li.innerHTML = h1[0].innerHTML;
// h1[0].parentElement.removeChild(h1[0]);// If you want to preserve H1s, remove this line
ul.appendChild(li); // Append the newly-created LI to the UL
}
parent.appendChild(ul); // Append the UL to the parent
}
This collects all H1 elements to an unordered list, which is appended to the parent element of the first H1.
A live demo at jsFiddle.

Categories