I am having trouble populating a ul li with its index value.
My HTML below.
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
My JS below.
$('document').ready(function(){
var indexus = $('li').index();
$('li').each(function(){
$('li').html(indexus);
});
});
JS Fiddle: http://jsfiddle.net/kuJWc/407/
I want to populate the li with its appropriate li index value, but I can only end up getting the index value of the latest (in this case 3). How would I go about looping in each index value so that each li shows the value of its own index number?
you should do like this:
$('li').each(function(){
$(this).html($(this).index());
});
you were adding the index to all the li.. so istead of $(this) inside of the each, you were using $('li'). which adds the last value li index to all of them.
Try this:
$('document').ready(function(){
$('li').each(function(){ // iterate through each `li`
var $li = $(this); // get the current `li` element
var index = $li.index(); // get the current `li` index
$li.html(index); // set the `li`'s html to the index value
});
});
I added some comments to help you understand what each step does, I hope that helps!
What about this:
$('document').ready(function(){
var indexus = $('li');
for (var i = 0; i <= indexus.length; i++) {
$(indexus[i]).html(i);
}
});
Here it works.
You can get an array of the ul's children and then iterate over each of the children with something like this:
var arr = $('ul').children();
for (var i = 0; i < arr.length; i++){
$(arr[i]).html(i);
}
Related
I have a list of LI in a UL, they are all dynamically added via jQuery. I am trying to alert the number of LI in this list. Right now I can only get it to alert 0. I think it is because its trying to count the original number on load? here is my code and fiddle:
https://jsfiddle.net/ts7Lwbfs/1
<ul id="list">
<li>original</li>
</ul>
var familly = []
familly.push('<li>1</li>');
familly.push('<li>2</li>');
familly.push('<li>3</li>');
familly.push('<li>4</li>');
$('#list').prepend(familly);
$('#list').on('click', 'li', function(ev){
var howMany = $('#list').length;
alert(howMany);
});
How can I get it to alert the total number of LI after they are dynamically added?
The selector $('#bet_slip') matches an element with the ID bet_slip, and as ID's are unique jQuery doesn't expect there to be more than one, and as none of your elements have that ID, you get zero?
Seems like what you want is to count the number of LI's in the #list list
$('#list').on('click', 'li', function(ev){
var howMany = $('#list li').length;
alert(howMany);
});
FIDDLE
Note that this counts all LI's currently present, including the one that was there originally.
If you are trying to find only the count of newly added li ( excluding the original ) , you can filter the li and exclude the first one using :not:first expression.
$('#list').on('click', function(ev){
var howMany = $(this).find('li:not(:first)').length;
alert(howMany);
});
https://jsfiddle.net/DinoMyte/ts7Lwbfs/4/
You can count the total number of list items this way:
$('#list').on('click', function(){
var howMany = $('#list li').length;
alert(howMany);
});
To get the number of added list items, first capture the count of original list items before you add new ones, and then subtract the total in your function from the original count.
var originalCnt = $('#list li').length;
$('#list').prepend(familly);
$('#list').on('click', function(){
var howMany = $('#list li').length - originalCnt;
alert(howMany);
});
Fiddle Demo
I have a problem I want to solve with jQuery. In a list, I want to check if two items have the same text, and if so I want to delete the second one.
I am not really sure how to go about it.
The markup is simple, kinda like this
<ul>
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
I cannot use an active/inactive class because this list is dynamic and I don't know in advance how it's going to be populated.
Any idea?
$.inArray for a tmp array would work.
$(document).ready(function(){
var tmparr = [];
$('.list li').each(function(i,item){
if($.inArray($(this).text(), tmparr) >= 0){
$(this).remove();
}else{
tmparr.push($(this).text());
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
<li>Text1</li>
<li>Text2</li>
<li>Text1</li>
<li>Text3</li>
<li>Text3</li>
<li>Text4</li>
<ul>
You can achieve this e.g. like this:
var unique = {};
$('li').each(function() {
var txt = $(this).text();
if (unique[txt])
$(this).remove();
else
unique[txt] = true;
});
Fiddle
As explanation: unique is initialized as object. While each() iterates over all li elements, the if (unique[txt]) is true in case it was previously set to true for the text of the li currently processed. In this case the current li will be removed. If not, unique[txt] for the text of the current li is set to true and added to unique. As it might not be clear what unique finally contains: { Text1=true, Text2=true, Text3=true, Text4=true }
You will need to iterate over your li elements and store their text in an array. If the text for the ith element is already in the array, skip it. Once you have an array of unique text strings, remove all li elements and generate new ones from the information in your array.
http://jsfiddle.net/k255o52e/1/
$('ul li').each(function () {
var txt = $(this).text();
// finds all LI that contain the same text
// excludes the first element
var $li = $('li:contains("' + txt + '"):not(:first)');
// and removes the other
$li.remove();
})
UPDATE:
$('ul li').each(function () {
var txt = $(this).text();
var $li = $('li:contains("' + txt + '"):not(:first)').filter(function(index)
{
return $(this).text() === txt;
});
$li.remove();
})
Newbie question - Is this code eloquent enough to create four list items? or Should I be using documentFragment instead? The code seems to work fine - JsFiddle.
Created list and li variables
var list = document.getElementById("myList");
var li = null;
Created x number of list elements and companion text nodes
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
Add li to list
list.appendChild(li);
}
Based entirely on the JSFiddle demo you've provided: No. What you currently have is semantically incorrect. You're currently appending your li to the body, not the ul element:
<ul></ul>
<li>Number 1</li>
Change:
document.body.appendChild(li);
To:
list.appendChild(li);
JSFiddle demo.
As for the code you've provided in the question, you also need to change it so that your li elements get appended to your ul element. You also need to change your class into an ID, as getElementById("myList") pulls an element with an ID of "myList", whereas your current ul has no such ID.
Actually there is an error, because you're adding the lis to the body instead of the ul
also the markup is not well created, change
<ul class="myList"></ul>
with
<ul id="myList"></ul>
To use an id and then:
var list = document.getElementById("myList");
var li = null;
for(var i=1; i<=4; i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode("Number " + i));
//document.body.appendChild(li); **error here**
list.appendChild(li); //fix
}
If i click the a element "Link1" e.target in the function is the node Link1. I want to know in what index this node is in the ul children in this case i want indexOf to return 0 because Link1 is on position 0, and i i click 2 i want it to be 1.
HTML
<div class="link">
<ul>
<li><a>Link1</a></li>
<li><a>Link2</a></li>
</ul>
</div>
JAVASCRIPT
self.query('.link').forEach(function(linkNode, flikIndex, flikArr) {
dojo.query(linkNode, 'click', function(e) {
var t = e.target; //If i click Link1 this is Link1 and if i click Link2 and so on.
var parent = t.parentNode; //Contains the parent to my a in this case li
var ancestor = t.parentNode.parentNode.childNodes; //Containes 2 li
var index = Array.prototype.indexOf.call(parent, ancestor); //Return -1 but i want it to return 0 because Link1 is on place [0] in the array.
}
}
Please help me get the right index
var index = Array.prototype.indexOf.call(parent, ancestor);
// ^ Array ^ Element in the array
So you want this:
var index = Array.prototype.indexOf.call(ancestor, parent);
Since ancestor is the element ("array") that contains parent.
Try this:
let nodes = Array.from( parent.closest('ul').children);
let index = nodes.indexOf(li);
When we work with a NodeList, getting the index of the li can be tricky using this approach:
var ancestor = t.parentNode.parentNode.childNodes;
var index = Array.prototype.indexOf.call(ancestor, parent);
If we have text in the lis, then these are also considered childNodes, and so the index of the li which is returned will be its index in the nodeList which consists of other children such as text, and not merely other lis. Therefore, you may not be getting the desired result in case you are only interested in the position of an li relative to the other lis in the ul
I have a large file of this form [similar div's throughout]. I want to be able to select a div, find the number of ul's in it and traverse through each of them to get value of each li in it.
<div class="experiment">
<div class="experiment-number">5</div>
<ul class="data-values">
<li><div></div> 14</li>
<li><div></div> 15</li>
</ul>
<ul class="data-values">
<li><div></div> 16</li>
</ul>
</div>
I have tried looping through all experiment divs, then select the uls, but it selects all the ul in the page, not only the ones under current div.
$('experiment ul').eq('$i');
Your HTML is currently incorrect, since you're simply starting new <div> and <ul> elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.
You need to select all of the <div class="experiment"> elements, then iterate through them. To do that you can use the .each() function. It might look something like this:
var experiments = $('.experiment'); // all of them
experiments.each(function(i, val) { // will iterate over that list, one at a time
var experiment = $(this); // this will be the specific div for this iteration
console.log("Experiment: " + experiment.find('.experiment-number').text());
// outputs the experiment number
console.log("Experiment ULs: " + experiment.find('ul').length);
// number of <ul> elements in this <div>
var total = 0;
experiment.find('ul.data-values li').each(function() {
total += parseInt($(this).text(), 10);
});
console.log("Experiment total: " + total);
// outputs the total of the <li> elements text values
});
Take a look at this jsFiddle demo.
to get all the ul inside div.experiment
var ul = $('.experiment').find('ul');
and to get all li elements inside each ul found above
ul.each(function(list) {
var li = $(list).find('li');
});
$('.experiment').each(function() {
var cnt = $(this).children('ul').length;
$(this).find('.experiment-number').text(cnt);
});
First of all you need to work out the correct selector for each DIV.
The selector you want is:
".experiment"
Notice the . to denote a class selector.
This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:
$(".experiment").each(function(){
var div = $(this);
var elementsInThisDiv = div.find("ul");
//you now have a list of all UL elements in the current DIV only
var numberOfElements = elementsInThisDiv.length;
//you now have a count of UL elements belonging to this DIV only
//you can loop the UL elements here
$(elementsInThisDiv).each(function(){
var ul = $(this);
//do something with the UL element
//like get the LI elements...
var liElements = ul.find("li");
});
});
IMPORTANT: There is also an error with your HTML, you need to close your <ul> elements correctly using </ul>