get text of the first li element from every ul - javascript

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)

Related

jQuery: assign array values to another set of elements

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++;
});
});

How to find index of li which doesn't have id?

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()

Count how many UL Elements there are in a Div with Javascript?

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);

loop through list with sublists javascript

ul
li1
li2
ul3
li3.1
li3.2
ul3.3
ul3.3.1
ul3.3.2
li4
li5
and I must check all items in ul3 I can't be sure if there is only two or three or more lists
Well, I don't know what you mean by "check", but you can have a function be called for each <li> like this:
$('li').each(function() {
// whatever "check" means
});
With just plain Javascript:
var nodes = document.getElementsByTagName('li');
for (var i = 0; i < nodes.length; ++i) {
var li = nodes[i];
// check ...
}
edit — well it's not clear what exactly you need, but if you just need to inspect <li> elements in lists that are themselves in <li> elements, then you'd just code that into the jQuery selector:
$('ul ul li').each(function() { ... });
Use the each() like this:
$('ul li').each(function(){
// your code.....
});
This will loop through the ul children at any nested level.
Update:
and I must check all items in ul3 I
can't be sure if there is only two or
three or more lists
Try this in that case:
$('ul:eq(2) li').each(function(){
// your code.....
});
This will start from third ul and find its children at any nested level.

Checking for length of ul and removing an li element

I am trying to remove the last <li> element from a <ul> element only if it exceeds a particular length. For this, I am doing something like this:
var selector = "#ulelement"
if($(selector).children().length > threshold) {
$(selector + " >:last").remove();
}
I don't like the fact that I have to use the selector twice. Is there a shorter way to do this? Something like a "remove-if-length-greater-than-threshold" idea. I was thinking that maybe there is a way to do this using the live() function but I have no idea how.
It is common to cache the results of your selector. Here, you can search for the <li>s directly:
var lis = $("#ulelement li");
if(lis.length > threshold) {
lis.eq(lis.length - 1).remove();
}
In this case you can also achieve this with a single selector:
$("#ulelement li:gt(4):last").remove();
That is: Among all <li> with index greater than 4 (or your threshold), select the last and remove it.
var ul = document.getElementById('myUL');
if (ul.childNodes.length > threshold)
ul.lastChild.parentNode.removeChild(ul.lastChild);
Hope that helped.
selector = '#ulelement';
while($(selector).children().length > threshHold)
{
$(selector + " li:last").remove();
}
Try using a while loop, as your code only runs once, the while will loop untill its less than thresh hold!

Categories