JavaScript
var sessions = [];
$('.rightDiv').each(function(index) {
var session = $.trim($(this).text().slice(0, -1)).split("×");
var sessionData = [];
for (var i = 0; i < session.length; i++) {
var ids = $(this).find('li').data('id');
var s = {
subjectOrder: i,
subjectID: ids
};
sessionData.push(s);
}
var ses = {
sessionNo: index,
sessionData: sessionData
};
sessions.push(ses);
});
HTML
<ul id="form_builder_sortable_sample" class="sortable rightDiv session4 ui-sortable">
<li class="draggable" data-id="1" name="Counting" >Counting<button onclick="deleteElement(event)" class="delbtn">×</button></li>
<li class="draggable" data-id="2" name="Priorities" >Priorities" class="delbtn">×</button></li>
</ul>
JSON
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"1"}]}
My Problem
What the code above does, is retrieves the session no from the ul class: class="sortable rightDiv session4" and each id of the li from data-id.
In this case it loops fine through the li items, but it only displays the id of the first li element.
It should be:
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"2"}]}
Any idea what's wrong?
Since you are using $(this).find('li').data('id');, it will always return the value of first li data attribute.
Use .each() to iterate and create an array
var sessionData = [];
$(this).find('li').each(function (index, elem) {
sessionData.push({
subjectOrder: index,
subjectID: $(elem).data('id')
});
})
change:
var ids = $(this).find('li').data('id');
to:
var ids = $(this).find('li').eq(i).data('id');
Related
I need to concatenate all the title value starting from second li elements with Javascript.
The problem is that I want to use it in different pages, so I can't know the exact number of li elements.
<div id="breadcrumb">
<ul>
<li title="One">One</li>
<li title="Two">Two</li>
<li title="Three">Three</li>
<li title="Four">Four</li>
</ul>
</div>
I use a variable for each element but if one or more element is missing the var is not valid and the concat function doesn't work.
var a = document.querySelector(".breadcrumb li:nth-child(2) > a").getAttribute("title");
var b = document.querySelector(".breadcrumb li:nth-child(3) > a").getAttribute("title");
var c = document.querySelector(".breadcrumb li:nth-child(4) > a").getAttribute("title");
var d = document.querySelector(".breadcrumb li:nth-child(4) > a").getAttribute("title");
var str = a.concat(b,c,d);
console.log(str)
Is there a way to do that?
Use querySelectorAll() and map():
const res = [...document.querySelectorAll("#breadcrumb li:not(:first-of-type)")].map(el => el.getAttribute("title")).join(" ")
console.log(res)
<div id="breadcrumb">
<ul>
<li title="One">One</li>
<li title="Two">Two</li>
<li title="Three">Three</li>
<li title="Four">Four</li>
</ul>
</div>
Using a little jquery i achieved this and it should solve your issues.
let list = [];
$('#breadcrumb li').each(function(i){
if(i !== 0) { list.push($(this).attr('title')); }
});
list.toString() //One,Two,Three,Four
The method you tried to use wont scale on a large list
Two minor remarks:
If you want to access the id=breadcrumb, you have to use #breadcrumb instead of .breadcrumb
There is no a tag in your HTML-code, therefore your querySelector won't give you any result
However, let's discuss a solution:
let listElements = document.querySelectorAll("#breadcrumbs li"); // get all list elements
listElements = Array.from(listElements); // convert the NodeList to an Array
listElements = listElements.filter((value, index) => index >= 1); // remove the first element
let titleAttributes = listElements.map(listElement => listElement.getAttribute("title")); // get the title attributes for every list elements. The result is an array of strings containing the title
console.log(titleAttributes.join(", ")); // concatenate the titles by comma
You can write the above statements in a single line:
Array.from(document.querySelectorAll("#breadcrumbs li"))
.filter((value, index) => index >= 1)
.map(listElement => listElement.getAttribute("title"))
.join(", ");
EDIT: I fix my answer, thanks to Barmar
something like that ?
const All_LI = [...document.querySelectorAll('#breadcrumb li')];
let a = ''
for (let i=1; i<All_LI.length; i++) { a += All_LI[i].title }
console.log('a-> ', a )
// .. or :
const b = All_LI.reduce((a,e,i)=>a+=(i>0)?e.title:'', '' )
console.log('b-> ', b )
<div id="breadcrumb">
<ul>
<li title="One">One</li>
<li title="Two">Two</li>
<li title="Three">Three</li>
<li title="Four">Four</li>
</ul>
</div>
I'm trying to convert something like this HTML snippet:
<ul>
<li><span>Frank</span><img src="pic.jpg"></li>
<li><span>Steve</span><img src="pic2.jpg"></li>
</ul>
into a JavaScript objects that contain the name and the image's url. How can I do that?
Use map() method
var res = $('ul li').map(function() { // select all li and iterate
// return as required format of array elemnt
return {
name: $('span', this).text(), // get text in span
src: $('img', this).attr('src') // get src attribute
}
}).get(); // get array from jquery object
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
UPDATE : If you want to generate an object which has key as span text and value as src attribute then use each() method and iterate over elements and generate object.
var res = {};
$('ul li').each(function() { // select all li and iterate
res[$('span', this).text().trim()] = $('img', this).attr('src');
})
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
var objs = document.querySelectorAll('.to-js-obj li');
var objs_arr = [];
if (objs) {
for (var i = 0; i < objs.length; i++) {
var name = objs[i].querySelector('span').innerText;
var url = objs[i].querySelector('img').src;
objs_arr.push({
name: name,
src: url
});
}
console.log(JSON.stringify(objs_arr));
}
<ul class="to-js-obj">
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
Using jQuery
var $list = $('ul'), // get the list (ideally, add an ID)
$listItems = $list.find('li'); // find list items
if( $listItems.length > 0 ) { // if list items exist
var images = []; // create empty array to store objects
$.each( $listItems, function( index ) { // loop through the list items
var $item = $( $listItems[index] ); // save item as jQuery element
var name = $item.find('span').text(); // Get name from span
var imageSrc = $item.find('img').attr('src'); // Get img src
images[index] = {}; // Create new object in array
images[index].name = name; // Add name
images[index].imageSrc = imageSrc; // Add source
});
}
Returns
[Object {
imageSrc: "pic.jpg",
name: "Frank"
}, Object {
imageSrc: "pic2.jpg",
name: "Steve"
}]
You can use this:
var image_pairs = [];
$("ul li").each(function() {
image_pairs.push({
name: $(this).find("span").text(),
url: $(this).find("img").attr("src")
});
});
console.log(image_pairs);
<ul>
<li><span>Frank</span><img src="pic.jpg"></li>
<li><span>Steve</span><img src="pic2.jpg"></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I have to embed some tracking code on my site. So I have a list of LI elements with an ID value that I want to place inside an array of the snippet. They should be numeric like, 123, 456, etc inside an object. I want to do it in pure JavaScript.
This is my code I have tried. My HTML:
<ul id="itemGrid">
<li class="item" id="1080"> product code </li>
<li class="item" id="1487"> product code </li>
<li class="item" id="1488"> product code </li>
...
</ul>
This is the JavaScript code
// Get all LI items and get the ID of them in the object viewList
var catId = document.getElementById('itemGrid').getElementsByTagName('li');
window.criteo_q = window.criteo_q || [];
window.criteo_q.push(
// SHOULD BE LIKE THIS
// { event: "viewList", item: ["First item id", "Second item id", "Third item id"] }
// My actual code
{ event: "viewList", item: [ catId[].id ] }
);
try this
var lis = document.getElementById('itemGrid').getElementsByTagName('li');
var idArray = [];
for ( var counter = 0; counter < lis.length; counter++)
{
idArray.push( lis[ counter ].id );
}
console.log( idArray );
You can use querySelectorAll to select all the matching elements passed as selector.
The selector '#itemGrid li[id]' will select all the <li> elements inside #itemGrid element having id attribute on it.
The querySelectorAll returns a collection of HTML elements. Iterate over this collection to get the individual element id.
var lis = document.querySelectorAll('#itemGrid li[id]');
var arr = [];
for (var i = 0; i < lis.length; i++) {
arr.push(+lis[i].id);
}
console.log(arr);
document.write('<pre>' + JSON.stringify(arr, 0, 4) + '</pre>');
<ul id="itemGrid">
<li class="item" id="1080">1080</li>
<li class="item" id="1487">1487</li>
<li class="item" id="1488">1488</li>
</ul>
<hr />
You can convert your HTMLCollection to an Array by passing it through slice, and you can then map that array:
catId = Array.prototype.slice.call(catId).map(function(li) { return li.id; });
var catId = document.getElementById('itemGrid').getElementsByTagName('li');
catId = Array.prototype.slice.call(catId).map(function(li) { return li.id; });
document.write(catId);
<ul id="itemGrid">
<li class="item" id="1080"> product code </li>
<li class="item" id="1487"> product code </li>
<li class="item" id="1488"> product code </li>
</ul>
var lis = document.getElementById('itemGrid').getElementsByTagName('li');
var arr = [];
// You need to iterate the list lis
[].forEach.call( lis, function(el){
arr.push( el.id );
});
// Making the object you want
var criteo_q = { event: "viewList", item: arr };
console.log(criteo_q);
To iterate the list of DOM elements, you can also use
I have a list like this:
<ul id="list">
<li>Adam</li>
<li>Alex</li>
...
<li>Zara</li>
</ul>
And it is already alphabetical ordered by this JavaScript:
var mylist = $('#list');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
Now I need to set the list like this:
<ul id="list">
<li id="a"><a name="a" class="title">A</a>
<ul>
<li>Adam</li>
<li>Alex</li>
</ul>
</li>
<li id="b"><a name="b" class="title">B</a>
<ul>
<li>Barry</li>
<li>Becky</li>
</ul>
</li>
...
...
...
<li id="z"><a name="z" class="title">z</a>
<ul>
<li>zavv</li>
<li>zora</li>
</ul>
</li>
</ul>
To use the list in this Apple Style Slider.
Do you know how can I do it with JavaScript?
It would be easiest (I guess) to collect all li elements in an object first (categorized bei their content's initial letter) and then sort those lists separately. Since code says more than a thousand words, here's how I would do that:
var list = { letters: [] }; //object to collect the li elements and a list of initial letters
$("#list").children("li").each(function(){
var itmLetter = $(this).text().substring(0,1).toUpperCase();
if (!(itmLetter in list)) {
list[itmLetter] = [];
list.letters.push(itmLetter);
}
list[itmLetter].push($(this)); //add li element to the letter's array in the list object
});
list.letters.sort(); //sort all available letters to iterate over them
$.each(list.letters, function(i, letter){
list[letter].sort(function(a, b) {
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase()); //sort li elements of one letter
});
var ul = $("<ul/>"); //create new dom element and add li elements
$.each(list[letter], function(idx, itm){
ul.append(itm);
});
$("#list").append($("<li/>").append($("<a/>").attr("name", letter.toLowerCase()).addClass("title").html(letter)).append(ul)); //add the list to a new li and to #list ul
});
JSFiddle: http://jsfiddle.net/KnC6M/
Thanks #Aletheios, I updated your solution to make it more efficient solution with the use of css without removing list by $("#list").empty();
Assuming your list is already sorted.
var letters = [];
$("#list").children("li").each(function(i){
var itmLetter = $(this).text().trim().substring(0,1).toUpperCase();
if (letters.indexOf(itmLetter)<0) {
console.log(`${itmLetter} is not in ${letters} and index is ${i}`);
$(`#list li:nth-child(${i+1})`).addClass("AddContent").attr('data-content',itmLetter);
letters.push(itmLetter);
} else {
console.log(`${itmLetter} is in ${letters}`);
}
});
CSS:
#list{
margin-left: 15px;
}
li.AddContent:before {
content: attr(data-content);
margin-left: -15px;
display: block;
}
HTML:
<ul id="list">
<li> Zara</li>
<li> Adam</li>
<li> Alex</li>
<li> Toby</li>
</ul>
JSfiddle: http://jsfiddle.net/KnC6M/105/
I was searching for something similar, I wanted to sort an array in alphabetically grouped manner. Here is my code which is little modified version of #Aletheios code. Hope it helps.
var list = { letters: [] };
var words = {let: ['abc', 'aabbgg', 'cda', 'hello', 'bca']};
$.each(words.let, function(){
var itLetter = this.substring(0,1).toUpperCase();
if(!(itLetter in list)){
list[itLetter] = [];
list.letters.push(itLetter);
}
list[itLetter].push($(this));
});
list.letters.sort();
$.each(list.letters, function(i, letter){
var ul = $("<ul/>");
var li = $('<li/>');
$.each(list[letter], function(idx, itm){
ul.append('<li>'+ itm[0] +'</li>');
console.log(itm);
});
$("body").append($("<li/>").append($("<a/>").attr("name", letter.toLowerCase()).addClass("title").html(letter)).append(ul));
});
Here is the fiddle.
http://jsfiddle.net/checkomkar/x8taqcnk/
Given the following structure:
<ul>
<li data-conference="Conference1" >Spain</li>
<li data-conference="Conference1" >France</li>
<li data-conference="Conference1" >Germany</li>
<li data-conference="Conference1" >Italy</li>
<li data-conference="Conference2" >Austria</li>
<li data-conference="Conference2" >Poland</li>
<li data-conference="Conference3" >Russia</li>
<li data-conference="Conference3" >USA</li>
<li data-conference="Conference3" >China</li>
</ul>
what is the best way (with jQuery), considering performance, to rearrange this into this:
<ul>
<li>Spain</li>
<li>France</li>
<li>Germany</li>
<li>Italy</li>
</ul>
<ul>
<li>Austria</li>
<li>Poland</li>
</ul>
<ul>
<li>Russia</li>
<li>USA</li>
<li>China</li>
</ul>
Thanks!
I think the overall question (group elements by attribute) is good, you just should have put more effort into trying to solve it yourself.
Anyways, grouping elements by an attribute is quite simple. You can create an attribute value -> [element, ...] map, which can be done with an object:
var groups = {};
$('li[data-city]').each(function() {
var attr = $(this).attr('data-city'),
group = groups[attr];
if(!group) {
group = groups[attr] = [];
}
group.push(this);
});
Now you have a collection of lists of DOM elements. You can iterate over the collection and create the HTML lists accordingly.
For example:
for(var group in groups) {
var $list = $('<ul />');
$list.append(groups[group]);
// now append $list somewhere
}
Have a look at Working with Objects [MDN] to get more information about how to process objects.
It's also trivial to do this without jQuery, as long as you have references to the elements, for example as a NodeList. Instead of using .each you can then use a "normal" for loop to iterate that list.
Unless you have a insane amount of cities in those lists I wouldn't worry about performance. The only performance consideration I would take is to avoid repaint / reflows by minimizing writing to the DOM. I think code clarity is much more important in this use case.
That being said I'd implement this with something like this - http://jsfiddle.net/XWufy/.
Here you go:
(function () {
var $list = $( '#list' );
var lists = {};
var $newLists = $();
$list.children().each( function () {
var city = $( this ).data( 'city' );
if ( !lists[ city ] ) lists[ city ] = [];
lists[ city ].push( this );
});
$.each( lists, function ( city, items ) {
var $newList = $( '<ul />' ).append( items );
$newLists = $newLists.add( $newList );
});
$list.replaceWith( $newLists );
}());
Live demo: http://jsfiddle.net/rjt9W/6/
Btw, the code assumes that the list has an ID of "list". Replace the selector in this line
var $list = $( ... );
so that it properly selects your UL element.
Use the data attribute as an object property to sort them, then loop over them to construct the new html. this should get you started:
var list = {};
// for each item
list[item.data('city')] = item.text();
// for each property of list
var ul = $('<ul>');
// for each listItem in current list
var li = $('<li>').text(listItem);
ul.append(li);
try this:
<ul id="first"></ul>// you can create the ul tags by using JavaScript
$("li").each(function(){
data = $(this).attr("data");
if (data == "Conference1") {
txt = $(this).text();
$("<li>" + txt + "</li>").appendTo("ul#first");
}
})
Try this:
var list = [];
var $div = $('#my_container_div');
$('li[data-city]').each(function() {
var $this = $(this), data = $this.attr('data-city');
list[ data ] = list[ data ] || [];
list[ data ].push( $this.text() );
});
for(var data in list) {
var $ul = $div.append('<ul/>');
for(var li in list[data]) {
$ul.append('<li>' + list[data][li] + '</li>');
}
}