add link to .textcontent in Javascript - 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')

Related

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

create a Edit Button while manipulating DOM in javascript

I am creating a simple TODO APP, which adds and deletes and edits a task when it's added, I am trying to figure out how to do edit a task. should I create a new P tag and equal it to par.value?
h1.innerText = 'TODO LIST';
document.body.appendChild(h1);
const input = document.createElement('input');
document.body.appendChild(input);
const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);
const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);
addBtn.addEventListener('click', function(){
const par = document.createElement('p');
par.innerText = input.value;
container.appendChild(par);
const deleteBtn =document.createElement('button');
deleteBtn.innerText = 'Delete';
par.appendChild(deleteBtn);
const editBtn = document.createElement('button');
editBtn.innerText = 'Edit';
par.appendChild(editBtn);
deleteBtn.addEventListener('click', function(){
this.parentElement.remove();
editBtn.addEventListener('click', function(){
})
})
})
There are many ways how you can do this. One way is to use the attribute contenteditable for your paragraph. See this example:
const h1 = document.createElement('h1');
h1.innerText = 'TODO LIST';
document.body.appendChild(h1);
const input = document.createElement('input');
document.body.appendChild(input);
const addBtn = document.createElement('button');
addBtn.innerText = 'Add';
document.body.appendChild(addBtn);
const container = document.createElement('div');
container.innerText = 'Output';
document.body.appendChild(container);
addBtn.addEventListener('click', function() {
const par = document.createElement('p');
par.innerText = input.value;
container.appendChild(par);
const deleteBtn = document.createElement('button');
deleteBtn.innerText = 'Delete';
container.appendChild(deleteBtn);
const editBtn = document.createElement('button');
editBtn.classList.add('edit');
editBtn.innerText = 'Edit';
container.appendChild(editBtn);
deleteBtn.addEventListener('click', function() {
this.parentElement.remove();
editBtn.addEventListener('click', function() {
})
})
})
// Since the selector ".edit" is dynamic, listen to all elements
document.querySelector('*').addEventListener('click', (e) => {
// Return, if the element has not the class "edit"
if (e.target.className !== 'edit') return
// Set attribute to the paragraph
e.target.previousSibling.previousSibling.setAttribute('contenteditable', 'true');
// focus the paragraph
e.target.previousSibling.previousSibling.focus();
});

javascript attributes clarification

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

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

DOM elements Javascript

I have append
cardBodyButton.addEventListener('click', function(){
listGroup.append(addTodo());
})
and I have a function
var addTodo = function(){
var todoList = document.createElement('li');
todoList.className = "list-group-item d-flex justify-content-between";
todoList.appendChild(document.createTextNode('Todo 5'));
var todoList_a = document.createElement('a');
todoList_a.className = "delete-item";
todoList_a.setAttribute('href','#');
var todoList_a_i = document.createElement('i');
todoList_a_i.className = "fa fa-remove";
todoList_a.append(todoList_a_i);
todoList.append(todoList_a);
};
I am trying to call function in append but it says undefined. What is wrong here?

Categories

Resources