Group list-items into sub-lists based on a data attribute - javascript

I want to append the <li> from one <ul> to another <ul> that's created on the fly. I want to group the list-items into new sub-lists based on their data-group attribute.
<ul id="sortable1">
<li data-group="A">test</li>
<li data-group="A">test1</li>
<li data-group="B">test2</li>
<li data-group="B">test3</li>
<li data-group="C">test4</li>
</ul>
Basically I'm trying to loop through this list and grap all <li> from each group, and then move it to another <ul>.
This is what I have so far, but I'm not getting the expected results. I have done this in Excel in the past but can't get it to work with jQuery.
var listItems = $("#sortable1").children("li");
listItems.each(function (idx, li) {
var product = $(li);
//grab current li
var str = $(this).text();
if (idx > 0) {
//append li
str += str;
if ($(this).data("group") != $(this).prev().data("group")) {
//I should be getting test and test1.
//but alert is only giving test1 test1.
alert(str);
//need to break into groups
//do something with groups
}
}
});

How about something like this:
$(function() {
var sortable = $("#sortable1"),
content = $("#content");
var groups = [];
sortable.find("li").each(function() {
var group = $(this).data("group");
if($.inArray(group, groups) === -1) {
groups.push(group);
}
});
groups.forEach(function(group) {
var liElements = sortable.find("li[data-group='" + group + "']"),
groupUl = $("<ul>").append(liElements);
content.append(groupUl);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="sortable1">
<li data-group="A">test</li>
<li data-group="A">test1</li>
<li data-group="B">test2</li>
<li data-group="B">test3</li>
<li data-group="C">test4</li>
</ul>
<div id="content">
</div>
I hope I didn't misunderstand you.

Related

Loop through ul li elements and get the li text excluding childrens

Hello how can i loop through ul li elements and get the text content only from the li, excepting the text content of its children?
<li class="lom">#paul<div class="on-off">offline</div></li>
<li class="lom">#alex<div class="on-off">offline</div></li>
<li class="lom">#jhon<div class="on-off">offline</div></li>
I want to get only the #paul without offline,
I have tried this:
var lnx = $('.cht(ul class) .lom');
for (let i = 0; i < lnx.length; i++) {
var txt = lnx[i].textContent;
console.log(txt + '\n');
}
But i get #pauloffline
Iterate through the .childNodes, filtering by nodeType of 3 (text node), to get only nodes that are text node children:
const texts = [...document.querySelector('.lom').childNodes]
.filter(node => node.nodeType === 3)
.map(node => node.textContent)
.join('');
console.log(texts);
<ul>
<li class="lom">#paul<div class="on-off">offline</div></li>
</ul>
Jquery solution using replace
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/replace
$('.lom').each(function(index, value) {
var getContent = $(this).text();
var replaceTxt = getContent.replace('<div class="on-off">offline</div>','').replace('offline','');
//$(this).find('.on-off').remove();
if (replaceTxt == '#paul') {
console.log(replaceTxt);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="lom">#paul<div class="on-off">offline</div></li>
<li class="lom">#alex<div class="on-off">offline</div></li>
<li class="lom">#jhon<div class="on-off">offline</div></li>
Here's a jQuery variant that uses the .ignore() micro plugin
$.fn.ignore = function(sel) {
return this.clone().find(sel||">*").remove().end();
};
// Get LI element by text
const $userLI = (text) =>
$(".lom").filter((i, el) => $(el).ignore().text().trim() === text);
// Use like
$userLI("#paul").css({color: "gold"});
<ul>
<li class="lom">#paul <span class="on-off">offline</span></li>
<li class="lom">#alex <span class="on-off">offline</span></li>
<li class="lom">#jhon <span class="on-off">offline</span></li>
<li class="lom">#paul</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

radomize ul tag not working

this is probably an easy question for you guys but I'm very new to coding and can't figure out this. I have a code that I want to randomize the given choices in the questions, and I've found a script online that does that but it's not working. I don't know what the
// shuffle only elements that don't have "group" class
$ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function() {
means so I tried to put all id that I don't need to randomize in it but it's still not working.
Can someone help me this please? Also is there anyway I can add choice "A", choice "B", choice "C", and choice "D" in front of each given options so even after the options(answers) are randomized, the A,B,C,D options will still be in order? Thank you. Here's the code:
HTML:
<!DOCTYPE html>
<html>
<body>
<script src="JQ.js"></script>
<script src="function.js"></script>
<link href="style.css" rel="stylesheet" />
<div id="quiz_container">
<ul class="quiz_container">
<li class="single_question" data-question-id="1" data-correct-answer="1">
<div class="question">
<h1 class="title">P.1 Grammar Review</h1>
<p class="text">1. "What is your name__"</p>
</div>
<ul class="options">
<li value="1">?</li>
<li value="2">.</li>
<li value="3">,</li>
</ul>
<div class="result"></div>
</li>
<li class="single_question" data-question-id="2" data-correct-answer="b">
<div class="question">
<p class="text">2. "Do you like the banana__"</p>
</div>
<ul class="options">
<li value="a">.</li>
<li value="b">?</li>
<li value="c">,</li>
</ul>
<div class="result"></div>
</li>
</div>
</body>
</html>
JS:
$(document).ready(function () {
/*
* shuffles the array
* #param {Array} myArray array to shuffle
*/
function shuffleArray(myArray) {
for (var i = myArray.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
return myArray;
}
var $ul, $li, li_content, li_list;
// find all lists to shuffle
$("#quiz_container > ul").each(function () {
$ul = $(this);
li_list = [];
// shuffle only elements that don't have "group" class
$ul.find("li[class!='single_question', 'question', 'title', 'text']").each(function () {
// add content to the array and remove item from the DOM
li_list.push($(this).html());
$(this).remove();
});
// shuffle the list
li_list = shuffleArray(li_list);
while (li_content = li_list.pop()) {
// create <li> element and put it back to the DOM
$li = $("<li />").html(li_content);
$ul.append($li);
}
});
$("#contact_div").show();
});
$(document).on('click', '.single_question .options li', function () {
// Save the question of the clicked option
question = $(this).parents('.single_question');
// Remove If Anyother option is already selected
question.find('.selected').removeClass('selected');
// Add selected class to the clicked li
$(this).addClass('selected');
// selected option value
selected_answer_value = $(this).attr("value");
// Value of correct answer from '.single-question' attribute
correct_answer_value = question.attr("data-correct-answer");
correct_answer_text = question.find('.options').find("li[value='" + correct_answer_value + "']").text();
if (correct_answer_value == selected_answer_value)
result = "<div class='correct'> Correct ! </div>";
else
result = "<div class='wrong'> Correct answer is -> " + correct_answer_text + "</div>";
// Write the result of the question
$(this).parents('.single_question').find('.result').html(result);
// Calculate the score
score_calculator();
});
/**
* It loops through every question and increments the value when "data-correct-answer" value and "option's value" are same
*/
function score_calculator() {
score = 0;
$('.single_question').each(function () {
question = $(this);
if (question.attr('data-correct-answer') == question.find('.selected').attr("value")) {
score++;
}
});
$('.correct_answers').html(score);
}
It looks like you're using jQuery, even though the question isn't tagged as such. If that's the case, you can use a code snippet written by Chris Coyier of CSS-Tricks called shuffle children.
Here's an example of the code in action.
$.fn.shuffleChildren = function() {
$.each(this.get(), function(index, el) {
var $el = $(el);
var $find = $el.children();
$find.sort(function() {
return 0.5 - Math.random();
});
$el.empty();
$find.appendTo($el);
});
};
$("ul.randomized").shuffleChildren();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Static List:</h4>
<ul>
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
<li>Fourth element</li>
</ul>
<h4>Randomized List:</h4>
<ul class="randomized">
<li>First element</li>
<li>Second element</li>
<li>Third element</li>
<li>Fourth element</li>
</ul>
In order to apply it to your own code, all you'd need to do is modify the CSS selector at the bottom of the jQuery snippet. In your case, ul.options might be a good choice.
Here are a couple of examples using your markup:
jsFiddle
Self-Contained HTML Doc

How do I get all the LI UL elements ID value and place them in a JavaScript array?

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

If submenu li has more than 5 li's create a new ul and place remaining list items?

I am basically trying to check if my submenu has more than five list items, and if it does grab the remaining list item's and place them inside a new ul that is outside of the current parent ul using jquery. it gets complicated because of the structure of the list.
Here is the DOM structure:
<ul id="nav" class="se test">
<li id="menu1" class="page-1307 parent-menu parent">
<div class="nav-inner">
<a class="menulink" id="menuitem1" onclick="return false" href="#">test<span class="toggle"></span></a>
<ul id="ie1" class="plain">
<li class="parent-menu parent">test<span class="toggle"></span>
<div class="submenu-wrapper">
<ul class="plain">
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</div>
</li>
<li class="parent-menu parent">test<span class="toggle"></span>
<div class="submenu-wrapper">
<ul class="plain">
<li>test</li>
<li>test</li>
<li>test</li>
<li>test</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
<li id="menu2" class="menulink page-7">
<div class="nav-inner">
test
</div>
</li>
</ul>
Basically i need to grab those remaining list items and place them in a new li.parent-menu.parent that includes the children div.sub-menu-wrapper and the ul.plain. the actual remaining list items would go inside the ul.plain of the new li.parent-menu. i hope thi makes since. i have been stuck on this for a day or two and unble to figure it out. any help would be greatly apprecitated, thank you.
This is what i am striving for, keep in mind it is dynamic.
you can:
Loop all ul in your document
foreach element count children
if found li number under an ul element is > 5
create a new list with the html of the required list
$(document).ready(function(){
$('.submenu-wrapper').each(function(){
var count_li=0;
var i=1;
$(this).children('ul').children('li').each(function(){
count_li++;
if(count_li>5 && i==1){
$(document.body).append('<ul id="newlist"></ul>');
$('#newlist').append($(this).nextUntil($(this).last()).andSelf());
i++;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul id="nav" class="se test">
<li id="menu1" class="page-1307 parent-menu parent">
<div class="nav-inner">
<a class="menulink" id="menuitem1" onclick="return false" href="#">test<span class="toggle"></span></a>
<ul id="ie1" class="plain">
<li class="parent-menu parent">test<span class="toggle"></span>
<div class="submenu-wrapper">
<ul class="plain">
<li>test11</li>
<li>test12</li>
<li>test13</li>
<li>test14</li>
<li>test15</li>
<li>test16</li>
<li>test17</li>
</ul>
</div>
</li>
<li class="parent-menu parent">test<span class="toggle"></span>
<div class="submenu-wrapper">
<ul class="plain">
<li>test21</li>
<li>test22</li>
<li>test23</li>
<li>test24</li>
</ul>
</div>
</li>
</ul>
</div>
</li>
<li id="menu2" class="menulink page-7">
<div class="nav-inner">
test
</div>
</li>
</ul>
Here is the final answer I was looking for:
megaMenu: function(){
function addNewList(current, newItems) {
var newList = $('<li class="parent-menu parent newLi">');
var div = $('<div class="submenu-wrapper">');
newList.append(div);
var ul = $('<ul class="plain">');
div.append(ul);
for (var i = 0; i < newItems.length; i++) {
ul.append(newItems[i]);
}
current.after(newList);
return newList;
}
function splitLists() {
var allLists = $(".plain > li.parent-menu");
for (var i = 0; i < allLists.length; i++) {
var currentList = $(allLists[i]);
var items = currentList.find("li");
if (items.length > 5) {
var temp = [];
for (var j = 5; j < items.length; j++) {
temp.push($(items[j]));
if (temp.length == 5) {
currentList = addNewList(currentList, temp);
temp = [];
}
}
if (temp.length > 0) {
currentList = addNewList(currentList, temp);
}
}
}
}
splitLists();
}
After some clarification via comments it seems you are looking for something like this. I have commented the code to explain the logic behind the process:
// function for adding a new LI item.
function addNewList(current, newItems) {
// Create the new li node.
var newList = $('<li class="parent-menu parent">');
// Add the initial a link.
newList.append('test<span class="toggle"></span>');
// Create and append the submenu-wrapper div to our new list item.
var div = $('<div class="submenu-wrapper">');
newList.append(div);
// Create and append the new ul node to our submenu-wrapper div.
var ul = $('<ul class="plain">');
div.append(ul);
// Loop the 5 (or less) items that have been specified and add them to our new list.
for (var i = 0; i < newItems.length; i++) {
// Using append will move the elements that already exist in the original place.
ul.append(newItems[i]);
}
// Add our new list item to the DOM.
current.after(newList);
return newList;
}
// Base function to split the lists as required.
function splitLists() {
// Get all the lists that we want to process.
var allLists = $(".plain > li.parent-menu");
// Loop each list and process.
for (var i = 0; i < allLists.length; i++) {
var currentList = $(allLists[i]);
// Get the sub-items that we need to split.
var items = currentList.find("li");
// We only care about lists that are more than 5 items.
if (items.length > 5) {
// Create array to store the items that we want to move (any after first 5)
var temp = [];
// Start at the 6th item an start moving them in blocks of 5.
for (var j = 5; j < items.length; j++) {
// Add the item to move to our temp array.
temp.push($(items[j]));
// If we have 5 in our temp array then move them to new list.
if (temp.length == 5) {
// Move items with helper function.
currentList = addNewList(currentList, temp);
// Clear the temp array ready for the next set of items.
temp = [];
}
}
// If we have any spare ones that didn't get handle in the length == 5 check, then process them now.
if (temp.length > 0) {
currentList = addNewList(currentList, temp);
}
}
}
}
// Run the process.
splitLists();
Here is a working example

Lists alphabetical ordered by javascript with letter headings

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/

Categories