How to add mutiple span to <li> javascript - 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>

Related

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

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>

Javascript issue with cell.innerHTML()

I am trying to provide the ability to have a FontAwesome glyph for certain table cells. This is achieved by using appropriate CSS classes, e.g. <i class="fa fa-check-square-o fa-2x foobar-stat-green"></i>
Here is the JS I have tried so far :
function addRow(tableID,rowData) {
if (Array.isArray(rowData) && rowData.length>0) {
var myTab=document.getElementById(tableID).getElementsByTagName('tbody')[0];
var newRow = myTab.insertRow();
rowData.forEach(function (item) {
console.log(item);
var newCell = newRow.insertCell();
// THIS : createTextNode + appendChild = WORKS OK (no "err") !
//var newText = document.createTextNode(item);
//newCell.appendChild(newText);
// SWITCHING TO THIS = WORKS OK (no "err" in console)
//newCell.innerHTML='';
// BUT THIS YIELDS "err" in console
//newCell.innerHTML(item);
});
}
}
Example input into this function would be :
var foobar = ['a','b','c','test+a#example.com','10/10/10 10:10','<i class="fa fa-check-square-o fa-2x foobar-status-green"></i>',false];
innerHTML is not a function, it's a property, you don't use parenthesis with it, write this directly :
newCell.innerHTML = item;
Without having to first write :
newCell.innerHTML = ''; // not needed
newCell.innerHtml is not a function defined on element. You need to use it as a setter. newCell.innerHtml = item.

Trying to sort a list in my html with javascript

im having a bit of trouble with the code below:
Html:
<p>click to <a onclick ="sortList(); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Javascript:
function sortList(listId) {
var list = document.getElementbyId(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
however, when i try and click the link to sort the html does nothing and im not sure what the problem is. i am referencing and was able to use changeit and echo function to produce an alert message in the .js file just cant sort
You need to pass the listId to the function as an argument like onclick ="sortList('fruits'); return false;" and change document.getElementbyId() to document.getElementById() which is a typo
function sortList(listId) {
var list = document.getElementById(listId);
var children = list.childNodes;
var listItemsHTML = new Array();
for (var i = 0; i < children.length; i++) {
if (children[i].nodeName === "LI") {
listItemsHTML.push(children[i].innerHTML);
}
}
console.log(listItemsHTML);
listItemsHTML.sort();
list.innerHTML="";
for (var i = 0; i < listItemsHTML.length; i++) {
list.innerHTML += "<li>" + listItemsHTML[i] + "</li>";
}
}
<p>click to <a onclick ="sortList('fruits'); return false;" href="#">sort</a></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
Firstly, it's document.getElementById ... capital B in ById
Secondly, use list.children rather than list.childNodes - don't need to care about text nodes
Thirdly, use list.appendChild on a sorted list to move the existing nodes, rather than mucking around with innerHTML
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort((a, b) => a.textContent > b.textContent).forEach(li => list.appendChild(li));
}
Or, if you're not comfortable with ES2015+
function sortList(listId) {
var list = document.getElementById(listId);
Array.from(list.children).sort(function (a, b) {
return a.textContent > b.textContent;
}).forEach(function (li) {
return list.appendChild(li);
});
}
and finally, change
<a onclick ="sortList(); return false;" href="#">
to
<a onclick ="sortList('fruits'); return false;" href="#">
I know its already answered, but of thought of providing little different version.
Use buttons instead of <a>, Using 'href='#' is not a good practice.
Never create a element from string. Always use document.createElement. Its better!
Write a separate listener for triggering functions. Don't write in HTML itself. It will be harder to manage once application grows.
HTML
<p>click to <button class="sort">sort</button></p>
<ul id="fruits">
<li>apple</li>
<li>orange</li>
<li>banana</li>
</ul>
JavaScript
<script type="text/javascript">
function sortList() {
var fruitCollection = [],
fruitsDOM = document.querySelector('#fruits'),
fruitsLists = document.querySelectorAll('li');
fruitsLists.forEach(function(item) {
fruitCollection.push(item.textContent);
});
fruitCollection.sort();
fruitsDOM.innerHTML = null;
fruitCollection.forEach(function(item) {
var newNode = document.createElement('li');
newNode.textContent = item;
fruitsDOM.appendChild(newNode);
});
}
document.querySelector('.sort').addEventListener('click', sortList);
</script>

Create links inside a list

I have a list looking like this
<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>
and want to make the text to links, with this result using JavaScript
<li class="list>text1</li>
<li class="list>text1</li>
<li class="list>text1</li>
I already did this, but don't know how to do next?
var link1 = document.createElement("a");
link.href = "#text1"
Is it possible to make a loop or something similar, so that I don't have to write the same code for all three links?
Yes, first you need to find all of the list class tags and loop through them.
var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {
Next find the text of the current list element, store it in a variable and then clear the element's text.
var text = lists[i].textContent;
lists[i].textContent = "";
Third, create the a element and make the textContent of the a element the text of the current list and the href, the current text plus the # sign.
var a = document.createElement("a");
a.href = "#"+text;
a.textContent = text;
And finally append the a to the current list element.
lists[i].appendChild(a);
var lists = document.getElementsByClassName("list");
for(var i=0; i<lists.length; i++) {
var text = lists[i].textContent;
lists[i].textContent = "";
var a = document.createElement("a");
a.href = "#"+text;
a.textContent = text;
lists[i].appendChild(a);
}
<li class="list">text1</li>
<li class="list">text2</li>
<li class="list">text3</li>
`
Iterate over the list elements adding the anchor HTML as a text replacement:
[].forEach.call(document.querySelectorAll('.list'), function (el) {
var txt = el.textContent;
el.innerHTML = '' + txt + '';
});
DEMO

Get list values in tag 'a' one by one using JavaScript

Here I am going to make a tag cloud manually.Everything is going well but I face a little problem. Below is my code :
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts">
</div>
</div>
JavaScript :
$(function() {
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
var count_li = $('#vis').find('#tagcloud_list').length+1;
for(var i=0; i < liArray.length ;i++){
for(var j = 0; j < count_li; j++){
if(i == j){
var get_item_value = ($(liArray[i]).text());
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
}
}
}
});
Output of this code is :
Item2
Item2
In this output both contain value 'Item2'.
But I want to get value 'item1' in first tag 'a' and value 'item2' in second tag 'a' .Like :
Item1
Item2
How I can get this?
HTML:
<ul id="tagCloud">
<li id="tagcloud_li">Item1</li>
<li id="tagcloud_li">Item2</li>
</ul>
<div id="vis">
<div class="set_texts"></div>
</div>
CSS:
.set_text {
height:500px;
width:500px;
background-color:#FFFFFF;
font-family:Arial;
border: 1px solid #FFFFFF;
text-align:left;
}
.tagcloud {
font-size:12px;
text-decoration:none;
color: #FF7600;
}
JS:
$(function () {
var container = $("#vis").find(".set_texts");
$("#tagCloud").find('li').each(function (i) {
$('<a href="" id="tagcloud_list" class="tagcloud tagcloud_li' + i + '"/>').text($(this).text()).appendTo(container);
});
});
Sample: (Fiddle)
Created tag cloud is simple but it's what your code does.
Your code is very complex and thus you won't see the point for sure. I.e.,
var liArray = document.getElementsByTagName('li');
var list_item = [];
for(var i=0; i < liArray.length ;i++){
list_item.push($(liArray[i]).text());
var get_item_value = ($(liArray[i]).text());
var create_text = $('#vis').find('.set_texts').append($('<a href="" id="tagcloud_list" class="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">'));
$('#vis').find(".tagcloud_li"+i).text($(liArray[i]).text());
}
might be reduced to this:
$("li").each(function() {
var item = $(this);
var text = item.text();
$('<a href="" class="tagcloud_list" id="tagcloud_li'+i+'" style="font-size:12px;text-decoration:none; color: #FF7600;">')
.text( text )
.appendTo( $('#vis').find('.set_texts') );
});
Your example of this loop is fetching same information from DOM several times and drops it in one of those cases. That's expensive by means of performance. Next you might reverse way of adding the <a> so you won't need to add it to the target container first just to get query that one to give it back afterwards.
The resulting <a> are all using same ID which is bad, too. So try swapping class and ID.
According to your issue this code seems to be crucial:
var get_class = $('#vis').find('a').text(get_item_value).append(get_class);
It is finding all <a> in your target assigning single text to all of them.
Change your Javascript to this.. And I used Jquery..
$(document).ready(function(){
var liArray = $("li");
var i;
for(i=0;i < liArray.length;i++){
$("div.set_texts").append('' + liArray[i].innerHTML + '');
}
});

Categories

Resources