Parse header to unordered list IN PLAIN JS - javascript

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.

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.

DOM function that creates an unordered list from an array

I have tried creating a DOM function that creates an unordered list from an array. For example if you pass it the array ["hello", "food", "sun"], it will create the unordered list:
<ul>
<li>hello</li>
<li>food</li>
<li>sun</li>
</ul>
However, it creates nothing.
Here is the code for my DOM function:
<script>
function create_list(array,id){
var ul= document.createElement("ul")
ul.setAttribute("id",id)
//sets the id of the ul tag to the id specified as argument.
for (var i=0 ; i<array.length ; i++){
ul.appendChild.document.createElement("li").textContent= array[i]
//creates list elements inside of the ul tag.
}
document.body.appendChild(ul)
//adds the ul tag to the body of the html document.
}
//call the function
create_list(["hello","13","Kitchen"],13)
</script>
Why is it not working and how can I make it work?
You should seperate the logic of creating a child and appending a child.
you error comes from ul.appendChild.document.createElement..
I think it's better to use like below =)
function create_list(array, id) {
var ul = document.createElement("ul")
ul.setAttribute("id", id)
//sets the id of the ul tag to the id specified as argument.
for (var i = 0; i < array.length; i++) {
var li = document.createElement("li");
li.textContent = array[i]
ul.appendChild(li);
//creates list elements inside of the ul tag.
}
document.body.appendChild(ul)
//adds the ul tag to the body of the html document.
}
//call the function
create_list(["hello", "13", "Kitchen"], 13)

For loop only loops 1 time - 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

Add multiple Li to Ul with javascript

With the onclick event I am trying to add mutliple LIs to UL, It wont add more than one Li with this method no matter how many appendChilds I do.
var form = document.getElementById("form");
var newUl = document.createElement('ul');
var newLi = document.createElement('li');
newButton.addEventListener("click", function(){
form.appendChild(newUl);
newUl.id = "formList";
var formList = document.getElementById("formList");
formList.appendChild(newLi);
formList.appendChild(newLi);
formList.appendChild(newLi);
}
//// html
<div id="form">
</div>
newLi is a reference to the node you wish to append to the formList. It can exist just once.
So, first time it executes formList.appendChild(newLi), it will append it to formList. Second time it executes, it would be removed from the first position and now added to second position. Same for third position.
You cannot append the same node multiple times using appenChild.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). This means that a node can't be in two points of the document simultaneously. So if the node already has a parent, the node is first removed, then appended at the new position.
Description at MDN
You have to make a separate element each time.
Try this:
var form = document.getElementById("form");
function newLi() {
return document.createElement("li");
}
newButton.addEventListener("click", function(){
//Create a separate <ul> each time, give it a class, and add it.
var newUl = document.createElement("ul");
newUl.class = "formList";
form.appendChild(newUl);
//create new <li>'s and append them
formList.appendChild(newLi());
formList.appendChild(newLi());
formList.appendChild(newLi());
//smile. :D
}
Unlike Muhammad, I assume that you want to create a separate unordered list (<ul>) each time.
Hence, whenever the button is clicked, we add a new <ul> and then append our <li>s into the new <ul>.
var form = document.getElementById("form");
var newUl = document.createElement('ul');
newUl.id = "formList";
form.appendChild(newUl);
newButton.addEventListener("click", function(){
var newLi = document.createElement('li');
newUl.appendChild(newLi);
})
You need to create the ul once, and assign to it the id = "formList", then append it to the form
On every click, create new li element
You don't need to select the ul again, because you already has a reference to it.
Here you can find a working fiddle https://jsfiddle.net/LeoAref/m5d0bzeL/
There's too much to correct in your post all at once. But if you're trying to template your LI, you can clone it using cloneNode
var template_ul = document.createElement('ul');
var template_li = document.createElement('li');
let newButton = document.getElementById('new');
var count = 0;
newButton.addEventListener("click", function() {
let list = template_ul.cloneNode();
document.getElementById('form').appendChild(list);
let first_li = template_li.cloneNode();
var text = document.createTextNode(++count);
first_li.appendChild(text);
list.appendChild(first_li);
list.appendChild(template_li.cloneNode());
list.appendChild(template_li.cloneNode());
});
body {
text-align:center;
}
button { margin: 4px auto 1em; }
ul {
margin: 0 auto 1em;
padding: 0;
width: 50%
}
ul:nth-child(2n) li{
background:#c90;
}
li {
list-style-type: none;
background: #09c;
height: 20px;
padding: 2px;
}
ul,
li {
border: 1px solid #444;
}
<button id="new">New</button>
<div id="form">
</div>
function addNode(){
var x = document.createElement("ul");
x.setAttribute("id","myList");
document.body.appendChild(x);
var myListItem = document.createElement("li");
var textNode = document.createTextNode("List Item one");
var t2 = document.createTextNode("second item");
myListItem.appendChild(textNode);
document.getElementById("myList").appendChild(newLi("FirstItem"));
document.getElementById("myList").appendChild(newLi("Second Item"));
document.getElementById("myList").appendChild(newLi("Third Item"));
document.getElementById("myList").appendChild(newLi("Fourth Item"));
}
//function which generates a new li tag and accepts a string for TextNode
function newLi(x)
{
var m = document.createElement("li");
var t = document.createTextNode(x);
m.appendChild(t);
return m;
}

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);
}

Categories