I have this code:
jQuery(document).ready(function($) {
var i = 0;
var values = [];
var element = $('.source');
element.each(function(i) {
values[i++] = $(this).text();
});
});
I want to assign each array value above, as the individual data-text value on another set of list elements. Something like this:
<ul id="list">
<li data-text="arrayvalue1"></li>
<li data-text="arrayvalue2"></li>
<li data-text="arrayvalue3"></li>
</ul>
I don't understand how I would do this using jQuery.
You can use attr() to assign data-text values with values from another array. With each() loop you are iterating over all li elements in ul and adding values from element array starting from 0, and you are also incrementing i by 1. So on second li, value of i will be 1 which is arrayvalue2 etc...
var element = ["arrayvalue1", "arrayvalue2", "arrayvalue3"]
var i = 0;
var values = $('ul li').each(function() {
return $(this).attr('data-text', element[i++]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list">
<li></li>
<li></li>
<li></li>
</ul>
Instead of using jQuery's each(), try using this higher order function.
I don't have a complete picture of how your object looks but something like this should work:
element.forEach((el) => {
el.dataset.text = referencedValue
}
There's no need for the "i" var, just do a push to the array of values. Like this:
jQuery(document).ready(function($) {
var values = [];
var element = $('.source');
element.each(function(i) {
values.push($(this).data('text'));
});
console.log(values);
});
See this fiddle https://jsfiddle.net/masqueradecircus/errq8cp7/3/
Provided you have your source elements you can iterate through them and apply the data attribute referring to the index of the element:
var element = $('.source');
element.each(function(i) {
$('#list > li').eq(i).attr('data-text', $(this).text());
//or
$('#list > li').eq(i).data('text', $(this).text());
});
Note: the difference of the two lines is:
.attr() will apply the value in the dom as an attribute to the element (visible in the html markup). The value can be retrieved with .data() or .attr()
The second one applies the value as an association to the element, which will not be reflected in the dom. This can only be retrieved with .data()
Example
Use $('.source li') and then you can use attr property in jquery to set the data-text attribute in another list.
Please find the sample below:
https://jsfiddle.net/vgade/km113ztL/
jQuery(document).ready(function($) {
var i = 0;
var values = [];
var element = $('.source li');
element.each(function(i) {
$('#destination li')[i].attr("data-text",$(this).text());
i++;
});
});
Related
There's an HTML page with 3 elements containing a class of ".list". Those ".list" elements have "li" elements in them, and in those "li" elements, there is text. I'd like to loop through all of "li" elements, and push their text to an array, with jQuery.
This is what I have so far:
var arr = [];
$(".list").each(function() {
this.children("li").each(function() {
arr.push(this.innerHTML);
});
});
However, I'm getting an error back from the console.
Error:
Uncaught TypeError: undefined is not a function
What am I doing wrong, and how can I fix it?
The value of this in your .each() loop will be a reference to an element, not a jQuery object. Thus:
$(".list").each(function() {
$(this).children("li").each(function() {
arr.push(this.innerHTML);
});
});
That is, $(this).children instead of this.children.
Note that you could avoid the outer .each() (not that there's anything terrible about it):
$(".list > li").each(function() {
arr.push(this.innerHTML);
});
Try following code. This will work for you
var arr = [];
var div = $(".list");
div.each(function() {
div.children("li").each(function() {
arr.push(this.innerHTML);
});
});
console.log(arr);
jsFiddle example
I'm attempting to use an ol to display several, dynamic, list items. Upon appending a list item using jQuery, I'd have hoped that the browser would've refreshed the ordered list, however it doesn't appear to be.
<ol>
<li value="1">First</li>
<li value="2">Second</li>
<li value="4">Forth</li>
</ol>
After appending <li value="3">Third</li>, the resulting order is:
// First
// Second
// Forth
// Third <-
Do I need to trigger a re-order, or is the order only calculated upon rendering the page / adding the list DOM element?
Note: I'm using Chrome 28.0.1500.95m
Firstly, note that value is not a valid attribute of li, so your code is invalid. You should use a data attribute for any non-standard attributes you require, the you need to write a sorter function. Try this:
$('#addThird').one('click', function() {
$('ol').append('<li data-value="3">Third</li>');
sortItems();
});
var sortItems = function() {
var $items = $('ol li');
$items.sort(function(a, b) {
var keyA = $(a).data('value');
var keyB = $(b).data('value');
return (keyA > keyB) ? 1 : 0;
});
$.each($items, function(index, row){
$('ol').append(row);
});
}
Updated fiddle
This sorts by the data-value attribute of the element, but that can be amended as required.
Hi I am creating tabs in JSP using twitter bootstrap.
<ul>
<li id="first">General</li>
<li>Transport</li>
<li>Data Map</li>
<li>Schedule</li>
</ul>
Now I have given id for first LI but dynamically I will be giving id to LI.
How to find the index of LI which does not have id? If the second one has no id, it should find the index of that LI only and should not check for remaining LI How can I get that?
Try with :not .first() and .index():
var idx = $('li:not([id])').first().index();
console.log(idx);
Demo
This will get you the index of first li which doesn't have an id.
You are probably looking for Siblings(). You could also get a reference to the Parent() and go from there.
$('ul li').each(function(index){
$(this).addClass('index-'+index);
});
Example here:
http://jsfiddle.net/superbshivam/HqpSF/
Very quick and dirty approach, but it should get you started on what you need.
var indexWithoutId = -1;
$(document).ready(function() {
findIndexWithoutId();
console.log("without id: " + indexWithoutId);
});
function findIndexWithoutId() {
$("li").each(function() {
var index = $(this).index();
var id = $(this).attr("id");
if (typeof(id) === "undefined") {
indexWithoutId = index;
return false;
}
});
}
Working jsfiddle example
jQuery has a function for this:
$('li').on('click',function(){
alert($(this).index());
});
NB: .index() returns a zero-based index.
Here is a working jsfiddle
To only target li's without an id, make use of the :not() selector and [id] attribute selector:
$('li:not([id])').on('click',function(){
alert($(this).index());
});
Updated jsFiddle
Source(s)
jQuery API - .index()
I have a lot of <ul> list and try to get from every first li of this list the text.
the markup is simple like:
<ul>
<li>abc</li>
<li>def</li>
<li>ghi</li>
</ul>
and so on.
my jQuery attempt is:
var elems = $('ul'); // returns a nodeList
var arr = jQuery.makeArray(elems);
arr.reverse(); // use an Array method on list of dom elements
for( var i=0; i < elems.length; i++) {
console.log($(this).find('li:lt(1)').text());
}
But I have a mistake in the for loop with $(this). I don't know how to get the first text of ul number 1 or 3 if i don't use $(this).
So how can point it correctly in the for loop?
.each will give you this.
$('ul').each(function() {
console.log($(this).find('li').eq(0).text());
})
Alternative sytax using :first instead of :eq(0)
$('ul').each(function() {
console.log($(this).find('li:first').text());
});
or, to forgo the find() function.
$('ul').each(function() {
console.log( $('li:first', this).text() );
});
you can also use:
$("li:nth-child(1)").each(function()
{
console.log($(this).text());
});
notes:
with :nth-child(n), all children are counted, regardless of what they are.
with :nth-child(n), n is 1-based (the first index is 1 instead of 0)
I am dynamically adding UL elements to a DIV element. I would like to be able to count how many UL elements there are inside the DIV so that once all the ULs are removed dynamically I can delete the DIV that they are contained in.
<div id="000">
<ul id="000-1">
<li>Stuff</li>
<li>Stuff</li>
</ul>
<ul id="000-2">
<li>Stuff</li>
<li>Stuff</li>
</ul>
</div>
Is there a simple Javascript solution that counts the amount of ULs so that I can do something like this.. ?
if(ulcount == 0){
var remove = document.getElementById("000");
remove.innerHTML = '';
results.parentNode.removeChild("000");
}
Thanks.
#Cheeso's answer is a good pure-JS solution. But, if you're using jQuery, the process can be made simpler.
jQuery('div#000').children('ul').length;
The above code will return the number of child ul elements of the div#000.
To update the count when you add elements dynamically, you will have to create a function and call it to update the number whenever a change occurs:
function countUls() {jQuery('div#000').children('ul').length;}
Bind that to an event so that it will be called when you want to update the number.
Code:
function getDirectChildrenByTagName(elt,tagname) {
var allChildren = elt.children, wantedChildren=[], i, L;
tagname = tagname.toUpperCase();
for(i=0, L=allChildren.length; i<L; i++) {
if (allChildren[i].tagName.toUpperCase() == tagname) {
wantedChildren.push(allChildren[i]);
}
}
return wantedChildren;
}
use it like this:
var zero = document.getElementById("000");
var uls = getDirectChildrenByTagName(zero, 'UL');
var ulCount = uls.length;
....
Try this:
var x = document.getElementById("000-1").querySelectorAll("li").length
console.log(">>>>", x);