javascript attributes clarification - javascript

please help,
why all 4 sections are linking to section 4 please?
i added the equivalent IDs and data attributes but they all link to section 4
//select the sections list
const sectionsList = document.querySelectorAll('.section');
//select the ul
const navBar = document.getElementById('navbar__list');
//transform the sections list to an array
const sectionsListArr = Array.from(sectionsList);
//iterate through the sections list
for (let i = 1; i <= sectionsListArr.length; i++) {
let text = "Section " + [i];
let li = document.createElement('li');
let link = document.createElement('a');
let newText = document.createTextNode(text);
//append the li items to the ul
link.appendChild(newText);
li.appendChild(link);
navBar.appendChild(li);
//link li items to their corresponding section
const dataAttribute1 = link.getAttribute('Section 1');
const dataAttribute2 = link.getAttribute('Section 2');
const dataAttribute3 = link.getAttribute('Section 3');
const dataAttribute4 = link.getAttribute('Section 4');
const setAttribute1 = link.setAttribute('href', '#section1');
const setAttribute2 = link.setAttribute('href', '#section2');
const setAttribute3 = link.setAttribute('href', '#section3');
const setAttribute4 = link.setAttribute('href', '#section4');
}

You may be looking for something like this. Each .section will need an unique ID, though.
const navBar = document.getElementById("navbar__list");
Array.from(document.querySelectorAll(".section")).forEach((section, i) => {
const link = document.createElement("a");
link.href = `#${section.id}`;
link.appendChild(document.createTextNode(`Section ${i + 1}`));
const li = document.createElement("li");
li.appendChild(link);
navBar.appendChild(li);
});

Related

How do I remove an object from an array on click? Javascript

I'm adding hours and dates which are displayed in a list and then pushing the values to an array.
A button is created next to each list item and I want to be able to remove the specific list item on click.
I've tried splice, slice and remove but I'm not able to make it work as I want.
let vacationList = [];
$('#add').click(function(e){
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
??
});
vacationList.push({vacationHours: Number(vacationHours), vacationDates: vacationDates});
Element.remove() should work for the dom element. If you want also remove from array please provide the adding to array code.
$('#add').click(function(e) {
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
this.closest("li").remove();
});
});

How to create a dynamic list, which removes deleted items from an array in JS?

I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.
For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin.
How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help.
Here is my code:
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
output.removeChild(paragraph)
})
})
You can find an element in the array by name and remove it from there:
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
output.removeChild(paragraph)
})
})
<input id="name">
<button id="button">button</button>
<div id="output">output</div>
Every time the event handler to delete an item is called, just collect all of the text of each item and convert it into an array.
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
/*
This removes an <li>, if you don't change your "paragraph" then
change 'li' to 'ul'
*/
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const item = document.createElement('li');
item.textContent = name+' ';
list.append(item);
const del = document.createElement('button');
del.textContent = "X";
item.append(del);
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});
<input id='user'><button class='add'>ADD</button>
<ul class='list'></ul>
Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const paragraph = document.createElement('div')
paragraph.style.display = 'flex'
const item = document.createElement('li');
item.textContent = name + ' ';
list.append(paragraph);
paragraph.append(item)
const del = document.createElement('button');
del.textContent = "X";
paragraph.append(del);
del.addEventListener('click', function() {
this.closest('div').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});

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

How to append child of child in javascript?

I have a div with a class called post, and I am iterating through a list of posts from the backend that I want to display on the front end.
My requirement is that I first want to create an empty div and append all the created elements in that div, and then finally push that div in the <div class = 'post'. But for some reason, it's giving me an error saying appendChild is not a function.
It would be great if I could convert this empty div element to look like below just through javascript. Since I want to style each of my posts and so I am wrapping them in a div.
EDIT: Below is my javascript code that I tried
for (let i = 0; i < paginatedItems.length; i++) {
let post_wrapper = document.createElement('div');
let post_element = document.querySelector('.post');
let hr = document.createElement('hr');
// Title of the blog
let title_element = document.createElement('h2')
title_element.classList.add('mt-4');
title_element.innerHTML = paginatedItems[i].title;
post_element.appendChild(title_element);
// Image of the Blog
let image_element = document.createElement('img');
image_element.classList.add('img-fluid');
image_element.classList.add('rounded');
image_element.style.width = '672'
image_element.style.height = '372'
image_element.src = paginatedItems[i].featured_image;
post_element.appendChild(image_element);
// Author Element
let author_element = document.createElement('p');
author_element.classList.add('lead');
author_element.innerHTML = 'By ';
let author_link = document.createElement('a')
author_link.innerHTML = paginatedItems[i].author.name;
author_link.href = 'google.com'
author_element.appendChild(author_link);
author_link.appendChild(hr);
post_element.appendChild(author_element);
// // Date Element
let date_element = document.createElement('p');
date_element.classList.add('item');
date_element.innerHTML = `Posted ${timeSince(paginatedItems[i].date)} ago`;
post_element.appendChild(date_element);
date_element.appendChild(hr);
// Description Element
let description_element = document.createElement('p');
description_element.classList.add('item');
description_element.innerHTML = paginatedItems[i].content.substr(0, 300) + '....';
post_element.appendChild(description_element);
// Show more button
let input_button = document.createElement('a')
input_button.classList.add('btn-primary');
input_button.classList.add('btn');
input_button.textContent = "Show more..";
input_button.addEventListener('click',
function () {
RenderPost(paginatedItems[i].ID);
}
)
console.log(post_element);
post_wrapper.appendChild(post_element);
post_element.appendChild(input_button);
}
you have to use forEach method.
here is an example:
const postsArray = [{title: 'miaw', id: 123324}, {title: 'hello', id: 983745}];
// the dom div you want to append to.
const myDiv = document.getElementById('[yourDivId]');
postsArray.forEach(post=>{
// creating the post
var div = document.createElement('div');
var title = document.createElement('h1');
var id = document.createElement('h4');
title.textContent = post.title;
id.textContent = post.id;
// appending the elements to a div
div.append(title, id);
// then appending the post to your div
myDiv.appendChild(div);
});
Getting element by id fixed it for me
here is the final working code snippet
let post_element = document.querySelector('#posts');
for (let i = 0; i < paginatedItems.length; i++) {
let post_wrapper = document.createElement('div');
let hr = document.createElement('hr');
// Title of the blog
let title_element = document.createElement('h2')
title_element.classList.add('mt-4');
title_element.innerHTML = paginatedItems[i].title;
post_wrapper.appendChild(title_element);
// Image of the Blog
let image_element = document.createElement('img');
image_element.classList.add('img-fluid');
image_element.classList.add('rounded');
image_element.style.width = '672'
image_element.style.height = '372'
image_element.src = paginatedItems[i].featured_image;
post_wrapper.appendChild(image_element);
post_element.appendChild(post_wrapper);
}

add link to .textcontent in Javascript

When I received help on adding a link to symbolSpan, I am now getting a link but the symbols are showing at the bottom of the page and not in the table with the rest of the data... How do I fix that?
const renderBalances = balances => {
//
binanceBalances.innerHTML = "";
//
//console.log(balances);
balances.forEach(balance => {
let balanceLi = document.createElement("li");
balanceLi.className = "list-group-item list-group-item-justify-content-center";
let balanceDiv = document.createElement("div");
balanceDiv.className = "d-flex w-100 justify-content-between";
let symbolSpan = document.createElement("span");
symbolSpan.textContent = balance.symbol;
// balanceDiv.appendChild(symbolSpan);
function createLink(linkExtension) {
const balanceDiv = document.createElement("div");
const symbolSpan = document.createElement("span");
const link = document.createElement("a");
link.setAttribute('href', `www.binance.com/en/trade/${linkExtension}`);
link.textContent = balance.symbol;
symbolSpan.appendChild(link);
balanceDiv.appendChild(symbolSpan);
document.body.appendChild(balanceDiv);
}
createLink('myparam')
this is the rest of the code for this table
let price = document.createElement("span");
price.textContent = balance.startPrice;
balanceDiv.appendChild(price);
let available = document.createElement("span");
available.textContent = balance.holdings;
balanceDiv.appendChild(available);
let onOrder = document.createElement("span");
onOrder.textContent = balance.used;
balanceDiv.appendChild(onOrder);
balanceLi.appendChild(balanceDiv);
binanceBalances.appendChild(balanceLi);
});
};
Create a span and a link html element. For the link element append the text and the href attribute.
Attach the link element to span and span to div. At last append to DOM.
Pass the additional parameter that needs to be appended to the link.
function createLink(linkExtension) {
const balanceDiv = document.createElement("div");
const symbolSpan = document.createElement("span");
const link = document.createElement("a");
link.setAttribute('href', `www.binance.com/en/trade/${linkExtension}`);
link.textContent = 'binance link';
symbolSpan.appendChild(link);
balanceDiv.appendChild(symbolSpan);
document.body.appendChild(balanceDiv);
}
createLink('myparam')

Categories

Resources