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

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/

Related

Get attributes for all (unknown) <li> elements with Javascript

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>

Continuously change text in an element

Hi all I have the following code :
var names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
$("#pickName").on('click', function () {
//pickName();
var name = names[Math.floor(Math.random() * names.length)];
alert(name);
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>
Which when I click on the #pickName selects a name from the array and displays it in a alert box then removes it from the array and from the <ul> list. Which is all fine but what I'd like to do is have the H1 tag (#randomName) looping through and 'flashing' all of the remaining names (constantly until I click #pickName).
I've tried doing an internet search for this but I can't think of how to word what it is that I'm trying to do!
Could anyone help?
You can do it using setInterval and by keeping a global counter, also take care to take the modulo of this counter with your array length to avoid out-of-bounds indexing.
Here is the doc for setInterval. You should also assign the return value so you can later clear your interval timer.
const names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
const h1$ = $('#randomName');
let idx = 0;
setInterval(() => {
h1$.text(names[idx++ % names.length]);
}, 200);
$("#pickName").on('click', function () {
const name = names[Math.floor(Math.random() * names.length)];
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>
Just like jo_va but having names going through randomly:
var names = Array('John', 'Craig', 'Jim', 'Nick', 'Stuart');
function pickName()
{
return names[Math.floor(Math.random() * names.length)]
}
$("#pickName").on('click', function () {
//pickName();
var name = pickName();
alert(name);
names.splice($.inArray(name, names), 1);
$('#' + name).remove();
});
setInterval(function(){
$("#randomName").text(pickName());
}, 200);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id="John">John</li>
<li id="Craig">Craig</li>
<li id="Stuart">Stuart</li>
<li id="Nick">Nick</li>
<li id="Jim">Jim</li>
</ul>
<a id="pickName">Click Me</a>
<h1 id="randomName"></h1>
Though, I recommend you find a more sustainable way to manage your elements rather than giving the <li> ids that match their content. Unless it's really meant for static use :)

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.

jQuery find element in ul li span

I have an HTML structure as:
<div title="" class="interestareascategories_chn chzn-container chzn-container-multi">
<ul id="ul_deptType" class="chzn-choices">
<li id="li_dept_1" ver="old" class="search-choice"> <span>DEV</span> <a rel="3" class="search-choice-close" seq="1" href="javascript:void(0)"></a>
</li>
<li id="li_dept_2" ver="old" class="search-choice"><span>QA</span> <a rel="3" class="search-choice-close" seq="2" href="javascript:void(0)"></a>
</li>
<li id="selD7J_chzn_c_3" class="search-choice"><span>sag</span> <a class="search-choice-close" seq="0.19415735425269753" href="javascript:void(0)"></a>
</li>
<li class="search-field"><span contenteditable="true" style="width: 25px;"></span>
</li>
</ul>
</div>
How to get only seq in anchor tag which have rel attribute?
Here's a fairly simple and straightforward answer:
// gets all anchors with attribute rel and place their [seq] values into an array
var values = $.map($('a[rel]'), function(el){
return el.getAttribute('seq');
});
console.log(values); // ["1", "2"]
live code sample
var seq = $("a[rel]").attr("seq");
Try this:
var anchor = $('a[rel][seq]'); // this only targets anchors which have these
// rel and seq attributes.
You can try this:
$('a[rel][seq]').on('click', function () {
alert($(this).attr('seq'));
});
Fiddle
You can use next selector for specific rel value
var seq3 = $("a[rel='3']").attr("seq");
To get sum of all sequences use next:
var sum = 0;
$.each($("a[rel='3']"), function(i, el)
{
sum += el.getAttribute("seq") | 0
})
jQuery(document).ready(function(){{
var check=jQuery(".search-choice a ").attr("rel");
if(check!="undefined")
{
var selVar=jQuery(this).attr("seq");
}
})
you should write a script like this, you can also store all "seq" value in an array.
You you want seq attribute of all anchors that have rel attribute then:
try like this:
$("a.search-choice-close").each(function(){
if($(this).attr('rel')) {
alert($(this).attr('seq'));
}
})
or :
$("a.search-choice-close[rel]").each(function(){
alert($(this).attr('seq'));
})
demo fiddle1
demo fiddle2
You can use something like:
http://jsfiddle.net/U2s7f/1/
$("a[rel]").map(function(i, el) { return $(el).attr("seq"); })
You can use an has attribute selector for rel and the get the value of seq attribute on the selected elements.
Code:
$('a[rel]').each(function(i,e){
console.log($(this).attr('seq'))
});
Demo: http://jsfiddle.net/IrvinDominin/VU3hr/

Storing only the text of a html list item in a javascript array and not the image src as well

In HTML I have an unordered list with items like
<ul id="sortable">
<li class="ui-state-default"><img src="images/john.jpg">John</li>
<li class="ui-state-default"><img src="images/lisa.jpg">Lisa</li>
<li class="ui-state-default"><img src="images/bill.jpg">Bill</li>
<li class="ui-state-default"><img src="images/sara.jpg">Sara</li>
</ul>
I want to store the names of a selected item in an array and the selection is working fine, the problem is that its also storing the img src as well as the name.
This is my code used to populate the array:
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
If I were then to output dataArr[0] I would get a return string of "< img src="images/ john.jpg ">John" when I obviously just want "John".
Try this: dataArr[idx] = $(elem).text();
.text() will give you only textual children of the node
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).text();
});
Use text() instead of html():
dataArr[idx] = $(elem).text();
Or, to be a little cheaper and avoid the cost of wrapping in a jQuery object each iteration:
dataArr[idx] = elem.textContent || elem.innerText;
References:
text().

Categories