JAVA SCRIPT - Applying a Striped Theme to an Unordered List

Applying a Striped Theme to an Unordered List


Problem

You want to modify the appearance of unordered list items so that the list appears striped.

Solution

Use the Selectors API to query for every other item in the list, and then change the background color by changing the class for the element or setting the style attribute on the element using setAttribute():


var lis = document.querySelectorAll('li:nth-child(2n+1)');
for (var i = 0; i < lis.length; i++) {
 lis[i].setAttribute("style","background-color: #ffeeee");
}
or
var lis = document.querySelectorAll('li:nth-child(odd)');
for (var i = 0; i < lis.length; i++) {
 lis[i].setAttribute("style","background-color: #eeeeff");
}
or access the list parent element and then traverse its child nodes, changing the back‐ ground color of every other element, using the arithmetic modulo operator:
var parentElement = document.getElementById("thelist");
var lis = parentElement.getElementsByTagName("li");
for (var i = 0; i < lis.length; i++) {
 if (i % 2 == 0) {
 lis[i].setAttribute("style","background-color: #eeffee");
 }
}

EXPLAIN 


 The :nth-child() pseudoclass allows us to specify an algorithm pattern, which can be used to find elements that match a certain pattern, such as 2n+1, to find every other element. You can also use the odd and even arguments to access the odd or even elements of the type:
var lis = document.querySelectorAll('li:nth-child(odd)');


Not all browsers support this selector type. Firefox, Opera, Safari, and Chrome do, but IE8 doesn’t support the first two approaches given in the solution, and older versions of most other browsers don’t. If you need to support older browsers, you’ll want to use the third approach in the solutions: get access to all of the elements using whatever method, and then use the modulo arithmetic operator to filter the elements. modulo returns the remainder of dividing the first operand by the second.


Dividing the numbers 0, 2, 4, 6, and so on by 2 returns 0, satisfying the conditional test, and the element’s style is altered. In the solution, the even elements are the ones altered. To alter the odd elements, use the following:


if ((i + 1) % 2) {
...
}

0 comments:

Post a Comment