jQuery Code Snippet: Automatically Set First List Item as Active in a Navigation Menu
using jQuery to select each <li> element within a <ul> and add the ‘active’ class to the first one. This code snippet is using the each function to iterate over each <li> element and applying the ‘active’ class to the one with index 0.
using jQuery to select each <li> element within a <ul> and add the ‘active’ class to the first one. This code snippet is using the each function to iterate over each <li> element and applying the ‘active’ class to the one with index 0.
$(‘ul li’).each(function(i) {
if ( i === 0 ) {
$(this).addClass(‘active’);
}
});
if ( i === 0 ) {
$(this).addClass(‘active’);
}
});
- 1- $('ul li'): Selects all <li> elements that are descendants of a <ul> element.
- 2- .each(function(i) { ... }): Iterates over each selected <li> element, and the function inside the each is executed for each iteration. The i parameter represents the index of the current <li> element in the iteration.
- 3- if (i === 0) { $(this).addClass('active'); }: Checks if the index i is equal to 0 (meaning it's the first <li> element), and if true, adds the 'active' class to that element using $(this).
- 4- So, essentially, this code sets the 'active' class on the first <li> element within the selected <ul> element.