For example, I have a div with an id (lets say "the_div"). This div contains an unordered list, and this list has 5 items in it.
How would I add a class to the third list item, without any of the list items having a class attached to them?
Edit: Even better, how would I change the list item text to equal what number element it was?
Thanks.
Or...
$('#the_div ul li:eq(2)').addClass('className');
You can combine the selectors together - if you prefer :)
For your first problem, you can use eq, which is 0 based:
$('ul li', '#thediv').eq(2).addClass('whatever'); // add class to 3rd item
For your second problem, you can use each to iterate through all the list items. The callback function passes an argument containing the index of the current element in the set:
$('ul li', '#thediv').each(function(i) {
$(this).text(i); // update each list item with its index, 0 based.
});
Related
I'm checking list items I have and if there are more than two then I add a class. This works fine but I want the class to start adding after the first two list items. I am not sure how to do that part that excludes adding the class to the first two. Here is my code:
$(document).ready(function() {
//Checking how many time the class appears
var numItems = $('ul.singleMagazine li').length;
if (numItems > 2) {
alert(numItems);
//Want to add this class but not to the first two - exclude first two list items and then add it to the rest. How to do it?
$('ul.singleMagazine li').addClass("newClass");
}
});
How I would do the excluding part?
The li elements should be siblings, so you can use the gt() selector:
$('ul.singleMagazine li:gt(1)').addClass("newClass");
Also note that the length check is redundant as if there's less than two items the above won't do anything anyway.
You can use gt selector. https://api.jquery.com/gt-selector/
$('ul.singleMagazine li:gt(1)').addClass("newClass");
This will add the class only to the li's which are greater than 1. Note here that the indexing starts from 0.
I am following a beginner video tutorial for Jquery and just went through this code: (inside .ready() )
$('ul li ').each(function(e){
$this().css{background' ,'red'}
$this().append(e);
});
now e prints each li index , can someone please explain me how does it get index for each item as it's not a loop .
Well, the .each() function is a loop. It almost literally says "For Each item that has the name 'ul li', do something."
The letter 'e' inside the parantheses is your actual index number. When you use an .each loop, the function gathers the number of whatever it's looking at and moves on until there are no more.
To simply show the number of the index, you can say:
$('ul li').each(function(i){ //I like to use the letter 'i' which more literally stands for 'index'
console.log(i);
});
This will show in your console as:
0
1
2
3
4
5
Assuming you have six of those elements.
Now, your use of $this means nothing. When using it properly it's written as $(this) which means "this element" since we're in a function that goes through each list element, it will take the list element it is currently looking at, then do whatever you want.
If you'd like the background color to be red of all of your list elements (like it seems you want to do) you would write:
$('ul li').each(function(i){
$(this).css({"background": "red"});
});
I'm not sure what you're trying to do with the .append function. By doing this, you're literally adding a list element to your list element for every list element!
Can you explain what you are trying to accomplish?
UPDATE
As your title says "Accessing every list item by its index," If you would like to access a particular list item, and not all of them, you can use the function .eq(). Let's say you have 6 list elements and you want the fourth one to have a red background. All you would have to do it this:
$('ul li').eq(3).css({"background":"red"});
Remember, index numbers start at zero, so the fourth one would be #3. (but of course, this would be faster and simpler in CSS!)
Actually, .each() is a loop/iterator. It will iterate over each of the elements that match. Eg: all the ul lis.
It will run through the code for every one it matches, and the DOM element will be accessible with $(this)
See the docs: http://api.jquery.com/jquery.each/
What would be the quickest way to go through all of the list items in one unordered list and remove all of the items after a specified list item?
Example: Let's say the list will always contain an item with the text "Hobbies." The javascript bit will have to find that item and remove all of the li items after it.
Using :contains and .nextAll:
$('li:contains("Hobbies.")').nextAll().hide();
Grab your item using the :contains selector to look for "Hobbies". Then you can grab all li items after it with nextAll() and remove() them.
This will hide all the li elements after the specific one
$('li').filter(function(index) { return $(this).text() === "Hobbies"; }).nextAll().hide();
I am using this code to add a class to every 7th LI items and the first one too:
$('ul li:first, ul li:nth-child(7n)').addClass("first");
$('ul li:first, ul li:nth-child(1)').addClass("first");
My problem is that it just adds the class to the 1st and the 7th item but if I add another 7 or more it doesn't add it.
I need to add the class the every 7th li item.
Try:
$('ul li:nth-child(7n+1)').addClass("first");
This will select every 7th element.
See demo on jsFiddle.
Use Jquery eq
The result of this call id adding a class first to every item 7. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.
$('ul li').eq(6).addClass("first");
I want to select all divs on a page whose children don't contain an element with a specific class.
I can select elements whose descendants do contain the class with:
$('div').has('.myClass');
So I just want the inverse of this.
I'd use ".filter()":
var theDivs = $('div').filter(function() {
return $(this).find('.myclass').length === 0;
});
A simple $("div:not(:has(.myClass))") will do the job.
How it works internally in jQuery?
1) $("div") - gets all DIVs from the document.
2) :not(:has(.myClass)) - These are two statements one nested in another. Now jQuery executes :has(.myClass) on resulted DIVs in above step and gets all DIVs with class name 'myClass'
3) :not() - This pseudo-selector method will be applied on All DIVs from Step 1 against the DIVs resulted from second statement to find DIVs without '.myClass'. This is possible by looping through all DIVs from Step 1 and comparing DIVs from second step.
$('div:not(:has(*>.myClass))');
$('div').has(':not(.myClass)');