How do I prevent textContent from overwriting the dynamically created span? - javascript

So I'm trying to insert an element into the list but the span keeps getting overwritten by the textcontent that I'm giving to li. This is what the code is supposed to look like:
<li class="togglable"><span class="plus-sgn">+</span> Add Task</li>
This is what I'm getting:
<li class="togglable">Add Task</li>
And here's the code:
const togglable = document.createElement('li');
const span = document.createElement('span');
togglable.className = 'togglable';
span.className = 'plus-sgn';
span.textContent = '+';
togglable.appendChild(span);
togglable.textContent = 'Add Task';
taskList.appendChild(togglable);

To create text node use document.createTextNode:
function add() {
const togglable = document.createElement('li');
togglable.className = 'togglable';
const span = document.createElement('span');
span.className = 'plus-sgn';
span.textContent = '+';
togglable.appendChild(span);
//append text as text node
togglable.appendChild(document.createTextNode('Add Task'));
taskList.appendChild(togglable);
}
add();
add();
add();
<ul id='taskList'>
<li>Abc</li>
</ul>

Maybe you can add it as follow:
const taskList = document.querySelector('ul#taskList');
const togglable = `<li class="togglable"><span class="plus-sgn">+</span> Add Task</li>`;
taskList.innerHTML += togglable;
<ul id="taskList"></ul>

Related

Customer List Challenge (TestDome)

I'm trying to solve this challenge from TestDome and i need some help. I dont really understand how i must toggle the email and how to append the item to DOM...
!!Please without Vanilla JS only!!
Implement the showCustomers function so that it renders customers as list items. The first argument to the function, customers, is an array of objects with the name and email properties. The second argument to the function, targetList, is an unordered HTML list to which each customer should be added as a separate list item.
The name and email properties should be added as two paragraphs inside the list item. At first, the email paragraph element should not be present in the DOM. The email paragraph element should be added to the DOM after the name is clicked, and it should be removed from the DOM when the name is clicked again.
For example, the following code:
document.body.innerHTML = `
<div>
<ul id="customers">
</ul>
</div>
`;
let customers = [{name: "John", email: "john#example.com"},
{name: "Mary", email: "mary#example.com"}];
showCustomers(customers, document.getElementById("customers"));
let customerParagraph = document.querySelectorAll("li > p")[0];
if(customerParagraph) {
customerParagraph.click();
}
console.log(document.body.innerHTML);
Should render:
<div>
<ul id="customers">
<li>
<p>John</p>
<p>john#example.com</p>
</li>
<li>
<p>Mary</p>
</li>
</ul>
</div>
THIS IS MY CODE
function showCustomers(customers, targetList) {
customers.forEach(item =>{
let res = `<li>
<p> ${item.name}</p>;
<p> ${item.email}</p>;
</li>;
targetList.innerHTML = targetList.appendChild(res);
})
}
https://www.testdome.com/questions/javascript/customer-list/49798?visibility=3&skillId=2
Replace the line
targetList.innerHTML = targetList.appendChild(res);
with
targetList.innerHTML += res;.
You basically have two ways for adding elements:
increasing innerHTML contents with raw strings
appending children to DOM element
In your case res is a string so you can't use targetList.appendChild
Since you asked :
'The email paragraph element should be added to the DOM after the name is clicked, and it should be removed from the DOM when the name is clicked again'.
create list el,create p el, create event listener on p el, append email to a child element
Replace your code to
customers.forEach((item) => {
const li = document.createElement("li");
const name = document.createElement("p");
name.textContent = item.name;
name.style.cursor = "pointer";
name.addEventListener("click", (event) => {
const parent = event.target.parentElement;
if (parent.children.length == 1) {
const email = document.createElement("p");
email.textContent = item.email;
parent.appendChild(email);
} else {
parent.lastChild.remove();
}
});
li.appendChild(name);
targetList.appendChild(li);
});
function showCustomers(customers, targetList) {
customers.forEach((customer, index) => {
const node = document.createElement('li');
let nameEl = document.createElement('p');
let emailEl = document.createElement('p');
nameEl.innerText = customer.name;
emailEl.innerText = customer.email;
node.appendChild(nameEl);
nameEl.addEventListener('click', function() {
node.contains(emailEl) ? node.removeChild(emailEl) :
node.appendChild(emailEl);
});
targetList.appendChild(node)
});
}

How to add a category to a drop down menu without using select and option HTML tags by manipulating the DOM

I want to add a category/restaurant to my drop down menu by typing a value into an input field. As you can see in my code, I am not using the <select> and <option>. When I add my JS code it gets an error:
TypeError: newRestaurant.add is not a function.
But when I changed the tags to <select> and <option> my JS code with the add() method worked.
<div class="dropdown">
<button class="locationSetter">WHERE ARE YOU?</button>
<ul class="dropdown-content">
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
<li><span>5</span></li>
<li><span>6</span></li>
<li><span>7</span></li>
</ul>
</div>
JS
// Drop Down function and adding the chosen location to the location setter
const locationSetter = document.querySelector('.locationSetter');
const dropdownContent = document.querySelector('.dropdown-content');
const locations = document.querySelector('span');
dropdownContent.addEventListener('click', e => {
if (e.target.tagName === 'SPAN') {
locationSetter.textContent = e.target.innerHTML;
locationSetter.style.color = 'blue';
locationSetter.style.fontSize = '18px';
}
});
// Adding a restaurant to the drop down menu
const addRestaurantInput = document.querySelector('.addRestaurantInput');
const restaurantListGenerator = newRestaurant => {
const html = `<li><span>${newRestaurant}</span></li>`;
//dropdownContent.innerHTML += html;
}
addRestaurantInput.addEventListener('submit', e => {
e.preventDefault();
const newRestaurant = addRestaurantInput.addnew.value.trim();
let option = document.createElement('span');
option.text = newRestaurant;
dropdownContent.add(option, dropdownContent[0]);
if (addRestaurantInput.length) {
restaurantListGenerator(addRestaurantInput);
addRestaurantInput.reset();
}
})
I would like to figure out if I can make the JS code work and I can add a restaurant/ value which has been typed into the input field using <ul> and <li> tag.
Currently I only work in Vanilla JS.
Any advice much appreciated.
Thanks!
<html>
<body>
<div class="dropdown">
<button class="locationSetter">WHERE ARE YOU?</button>
<input type="text" class="addRestaurantInput"/>
<ul class="dropdown-content">
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
<li><span>5</span></li>
<li><span>6</span></li>
<li><span>7</span></li>
</ul>
</div>
</body>
<script>
const locationSetter = document.querySelector('.locationSetter');
const dropdownContent = document.querySelector('.dropdown-content');
const locations = document.querySelector('span');
dropdownContent.addEventListener('click', e => {
if (e.target.tagName === 'SPAN') {
locationSetter.textContent = e.target.innerHTML;
locationSetter.style.color = 'blue';
locationSetter.style.fontSize = '18px';
}
});
// Adding a restaurant to the drop down menu
const addRestaurantInput = document.querySelector('.addRestaurantInput');
//const restaurantListGenerator = newRestaurant => {
// const html = `<li><span>${newRestaurant}</span></li>`;
//dropdownContent.innerHTML += html;
//}
addRestaurantInput.addEventListener('change', e => {
e.preventDefault();
const newRestaurant = e.target.value;
let elem = document.createElement("LI");
let span = document.createElement("SPAN");
let text = document.createTextNode(newRestaurant.toString());
span.appendChild(text);
elem.appendChild(span);
dropdownContent.appendChild(elem);
})
</script>
</html>
You just have to append the child in the ul element just by getting value from element when the input value is change.Just enter the value in input and press enter. It will append the value in list.
Hope this helps!!!

How to add mutiple span to <li> javascript

I need populate <li> using javascript. I tried this.
ASPX code:
<div class="col-xs-12" id="displayDiv" runat="server">
<ul id="servicesList" runat="server"></ul>
</div>
JavaScript:
function PopulateList() {
var json = "[ { \"Id\":1068, \"Name\":\"Doe\" }, { \"Id\":1070, \"Name\":\"Smith\" },{ \"Id\":1074, \"Name\":\"Jones\" } ]";
var obj = JSON.parse(json);
var list = document.getElementById('<%= servicesList.ClientID %>');
for (i = 0; i < obj.length; i++) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(obj[i].Name));
li.className = "drag-handle-container";
li.innerHTML = "<i class='fa fa-bars'></i>";
li.setAttribute("data-id", obj[i].Id);
list.appendChild(li);
}
}
But it's not populated I expected a list with SPAN I need this
<ul id="ctl00_ContentPlaceHolder1_servicesList">
<li class="sortable-service-item"><span class="drag-handle-container"><i class="fa fa-bars"></i></span><span style="display: none;">1068</span><span>Doe</span></li>
<li class="sortable-service-item"><span class="drag-handle-container"><i class="fa fa-bars"></i></span><span style="display: none;">1070</span><span>Smith</span></li>
<li class="sortable-service-item"><span class="drag-handle-container"><i class="fa fa-bars"></i></span><span style="display: none;">1074</span><span>Jones</span></li>
</ul>
According to my code, HTML generating as follows, but I need the above HTML
<ul id="ctl00_ContentPlaceHolder1_ViewProductService_servicesList">
<li class="drag-handle-container" data-id="1068"><i class="fa fa-bars"></i></li>
<li class="drag-handle-container" data-id="1070"><i class="fa fa-bars"></i></li>
<li class="drag-handle-container" data-id="1074"><i class="fa fa-bars"></i></li>
</ul>
How to populate above HTML code by using javascript for loop?
You are requesting a way to achieve your "above" HTML (as you mentioned) but your generated code is vastly different than that. There are "data-ids" , different class-names , etc. Nevertheless , taking for granted that your "above" code is your goal the following 2 ways will produce exactly that. The first way follows your path. Using Native Javascript createElement functions and appending them on DOM elements. The Second way creates a String that represents HTML Code and it inserts it into the DOM creating the whole List.
In both examples i use the Array.prototype.forEach() for the Array loops and the
Object.keys() for the Object loops. I also use Arrow functions in those loops which is not necessary though in this case.
1st Way
let json = "[ { \"Id\":1068, \"Name\":\"Doe\" }, { \"Id\":1070, \"Name\":\"Smith\" },{ \"Id\":1074, \"Name\":\"Jones\" } ]";
let obj = JSON.parse(json);
let list = document.getElementById('servicesList');
obj.forEach((ObjectRow)=>{
let li = document.createElement("li");
li.className = "sortable-service-item";
let Span = document.createElement("span");
Span.className = "drag-handle-container";
Span.innerHTML = "<i class='fa fa-bars'></i>";
Span.setAttribute("data-id", ObjectRow["Id"]);
li.appendChild(Span);
Object.keys(ObjectRow).forEach((key)=>{
let tempSpan = document.createElement("span");
tempSpan.innerHTML = ObjectRow[key];
li.appendChild(tempSpan);
});
list.appendChild(li);
});
2nd Way
let json = "[ { \"Id\":1068, \"Name\":\"Doe\" }, { \"Id\":1070, \"Name\":\"Smith\" },{ \"Id\":1074, \"Name\":\"Jones\" } ]";
let obj = JSON.parse(json);
let list = document.getElementById('servicesList');
let myHTML;
obj.forEach((ObjectRow)=>{
myHTML += "<li class='sortable-service-item'>" +
"<span class='drag-handle-container' data-id='"+ObjectRow["Id"]+"'>" +
"<i class='fa fa-bars'></i>" +
"</span>";
Object.keys(ObjectRow).forEach((key)=>{
myHTML += "<span>"+ObjectRow[key]+"</span>";
});
myHTML += "</li>";
});
list.insertAdjacentHTML("beforeEnd" , myHTML);
Please try updated code:
Change the value inside the for loop as per your requirement.
for (i = 0; i < 3; i++) {
var li = document.createElement("li");
li.className = "drag-handle-container";
var span_1 = document.createElement("span");
span_1.setAttribute('class', 'drag-handle-container');
span_1.innerHTML = '<i class="fa fa-bars"></i>';
li.appendChild(span_1);
var span_2 = document.createElement("span");
span_2.style.display = 'none';
span_2.innerHTML = '1068';
li.appendChild(span_2);
var span_3 = document.createElement("span");
span_3.innerHTML = 'Doe';
li.appendChild(span_3);
console.log(li);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I dont know why this code does not add li element

In console, am getting undefined, but I can't understand.
JS Fiddle
function createItem(element) {
var li = document.createElement('li');
li.innerText = element.value;
var ul = document.getElementById('todo');
ul.appendChild(li);
}
var element = document.getElementById("input")
document.getElementById("submit").onclick = createItem;
console.log(element);
Based on your fiddle, the form is being submitted, in order to prevent that in the below code I have used the event.preventDefault, and then you need to pass the element parameter to the createItem function.
function createItem(element) {
var li=document.createElement('li');
li.innerText=element.value;
var ul=document.getElementById('todo');
ul.appendChild(li);
}
var element = document.getElementById("input");
document.getElementById("submit").onclick=function(e){
event.preventDefault();
createItem(element);
};
try this :)
function createItem(element) {
var li = document.createElement('li');
li.innerText = document.getElementById("input").value;
var ul = document.getElementById('todo');
ul.appendChild(li);
}
var element = document.getElementById("input")
document.getElementById("submit").onclick = createItem;
console.log(element);
<ul id="todo">
</ul>
<input id="input" >? </input>
<button id="submit" />

Insert html code after element

I have a html document which looks like this:
...html code...
<ul id="my_ul">
...html code...
Using javascript I want to insert the html code below inside the document, immediately after <ul id="my_ul"> :
<li><span>Some text</span><ul>
So far I have this, but not the expected results. Please, what am I doing wrong?
var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
var para3 = document.createElement("ul");
var element = document.getElementById("my_ul");
element.appendChild(para1);
element.appendChild(para2);
element.appendChild(para3);
If you want shorter code without creating objects for each html elements just do this:
var element = document.getElementById("my_ul");
var html = '<li><span>Some text</span></li>';
element.innerHTML = html + element.innerHTML;
Like this:
var ul = document.getElementById("my_ul");
var li = document.createElement("li");
var span = document.createElement("span");
var text = document.createTextNode("Some text");
span.appendChild(text);
li.appendChild(span);
ul.appendChild(li);
<ul id="my_ul">
</ul>
Is this what you want to do?
Demo: Fiddle
var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
para1.appendChild(para2);
element = document.getElementById("my_ul");
element.appendChild(para1);
Your code does this:
element.appendChild(para1);
Make the list item a child of the original list
element.appendChild(para2);
Make the span a child of the original list
element.appendChild(para3);
Make the new list a child of the original list
You need to append each element to the element you want to be its parent instead of appending everything to the original list.
Replace element with the appropriate variable.
$(document).ready(function(){
var para1 = document.createElement("li");
var para2 = document.createElement("span");
var node = document.createTextNode("Some text");
para2.appendChild(node);
var element = document.getElementById("my_ul");
element.appendChild(para1);
para1.appendChild(para2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="my_ul">
</ul>
var ul = document.getElementById("my_ul");
var li = document.createElement("li");
var span = document.createElement("span");
var textNode = document.createTextNode("Some text");
span.appendChild(textNode);
li.appendChild(span);
ul.appendChild(li);

Categories

Resources