jQuery: Convert Attribute Values to Nested Array (Strings to Numbers) - javascript

Using jQuery, I would like to get each attribute value, insert it into an array and then insert each array into an array.
From this HTML:
<ul>
<li data-bbox="-121,20,-36,30">Item 1</li>
<li data-bbox="-122,30,-46,40">Item 2</li>
<li data-bbox="-123,40,-56,50">Item 3</li>
</ul>
I'm trying to create this type of nested array:
var bboxArray = [
[-121,20,-36,30],
[-122,30,-46,40],
[-123,40,-56,50]
];
...and convert the strings to numbers.
I'm assuming I need to do something like this:
var bboxArray = [];
$('li[data-bbox]').each(function() {
bboxArray.push($(this).attr('data-bbox').split(','));
});

Working Example
While your code does work, it is returning strings instead of the numbers you have in your required output this will do that:
I simply added .map(Number) at the end of your push
$('li[data-bbox]').each(function() {
bboxArray.push($(this).attr('data-bbox').split(',').map(Number));
});

You can use the .map() method like so:
var bboxArray = $('ul > li').map(function() {
return [ $(this).data('bbox').split(',') ];
}).get();
var bboxArray = $('ul > li').map(function() {
return [ $(this).data('bbox').split(',') ];
}).get();
console.log( bboxArray );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-bbox="-121,20,-36,30">Item 1</li>
<li data-bbox="-122,30,-46,40">Item 2</li>
<li data-bbox="-123,40,-56,50">Item 3</li>
</ul>

Related

How do I create a new object based on clicked element in ES6?

I'm developing a simple web game using ES6. There is an item list and the player can buy an item by clicking the list. The code is as follows:
index.html
<ul>
<li id="a">item A</li>
<li id="b">item B</li>
<li id="c">item C</li>
</ul>
items.js
class ItemA() {...}
class ItemB() {...}
class ItemC() {...}
index.js
myItems = [];
$('#a').on('click', () => {
let item = new ItemA();
myItems.push(item);
});
$('#b').on('click', () => {
let item = new ItemB();
myItems.push(item);
});
$('#c').on('click', () => {
let item = new ItemC();
myItems.push(item);
});
I can do this work, of course. However, if the number of items is 100 or more, I should write 100 or more event listeners. How can I solve this problem?
You could create one object where key is the id and value is the class.
class ItemA {}
class ItemB {}
class ItemC {}
let items = {
a: ItemA,
b: ItemB,
c: ItemC
}
let myItems = []
$("li").click(function() {
let id = $(this).attr("id");
myItems.push(new items[id]);
console.log(myItems)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li id="a">item A</li>
<li id="b">item B</li>
<li id="c">item C</li>
</ul>

When appending childnode, its throwing error "Property 'appendChild' does not exist on type 'NodeListOf<Element>'."

when appending child node to li , getting error like Property 'appendChild' does not exist on type 'NodeListOf'
let li: NodeListOf<Element> = document.querySelectorAll("name li");
var newItem = document.createElement("li");
var ListValue = document.createTextNode("abcd");
var ListValue = document.createTextNode("efgh");
var ListValue = document.createTextNode("ijkl");
newItem.appendChild(ListValue);
li.appendChild(ListItem);
document.querySelectorAll is an array and not an element, you should iterate over your li variable, but I'm guessing that you want to add an item to an existing list, if this is the case you should append the item to the list container <ul>...</ul>
EDIT: use document.querySelector to select only a specific element
Also, it's bad practice to define new custom html tags, try to use a class instead, so for an html like this:
<ul class="test">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
use this:
let li: NodeListOf<Element> = document.querySelector("ul.test");
var newNumberListItem = document.createElement("li");
var numberListValue = document.createTextNode("java");
var numberListValue = document.createTextNode("ajax");
var numberListValue = document.createTextNode("javascript");
newNumberListItem.appendChild(numberListValue);
li.appendChild(newNumberListItem);
Tip: if you are using ES6, avoid using var and use const for values that won't change on your scope and let for variables
let li: NodeListOf<Element> = document.querySelector("ul.test");
var newNumberListItem = document.createElement("li");
var numberListValue = document.createTextNode("java");
var numberListValue = document.createTextNode("ajax");
var numberListValue = document.createTextNode("javascript");
newNumberListItem.appendChild(numberListValue);
li.appendChild(newNumberListItem);
<ul class="test">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
li is a NodeListOf<Element>, it is not itself an Element so it does not have an appendChild method. Most likely what you wanted to do is address an element in your list:
li[0].appendChild(newNumberListItem);

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

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.

get an array of data-val values from a list of elements of a certain css class

I would like to get an array of the values from the data-val attributes of .my-li elements
<ul id="stuff">
<li class='my-li' data-val='1'>
<li class='my-li' data-val='2'>
<li class='my-li' data-val='3'>
<li class='my-li' data-val='4'>
<li class='my-li' data-val='5'>
<ul>
here the result should be [1,2,3,4,5];
anybody knows a good way of doing this ?
Try:
var foo = $('#stuff .my-li').map(function () {
return $(this).data('val');
});
try this simple one.
var array = [];
$('.my-li').each(function(){
array.push($(this).attr('data-val'));
});
alert(array);
fiddle : http://jsfiddle.net/pp5pw/
var foo = $('#stuff .my-li').map(function () {
return $(this).attr('data-val');
});
console.log(foo[0])
jsfiddle goes to http://jsfiddle.net/granjoy/KxQAr/

Change The Classes Of List Elements

I want to change the class of each list(#list) item to the correspondent one at an Array. I have a list that is like this:
<ul id="list">
<li>Banana</li>
<li>Apple</li>
<li>Pear</li>
<li>Strawberry</li>
<li>Lemon</li>
</ul>
And I have this array:
["ban", "appl", "per", "straw", "lemn"]
What I want is that jQuery .addClass() function to change each item with the class in the order as they are on the Array. To result into this:
<ul id="list">
<li class="ban">Banana</li>
<li class="appl">Apple</li>
<li class="per">Pear</li>
<li class="straw">Strawberry</li>
<li class="lemn">Lemon</li>
</ul>
How can I do it?
This should work for you:
var classes = ["ban", "appl", "per", "straw", "lemn"];
$('#list > li').addClass(function(index) {
return classes[index];
});
You can see the documentation for this overload (the one that takes a function(index, currentClass) callback) on the jQuery website.
$('#list > li').each(function(i){
$(this).addClass( myArray[i] );
});
var myArray = ["ban", "appl", "per", "straw", "lemn"];
$("#list > li").each(function(index) {
$(this).addClass(myArray[index]);
});
$.each(myArray, function(i, value){
$('#list li').eq(i).addClass(value);
}
);

Categories