So I need to figure out how to store "p" tags into an array, and then use the ternary operator to determine if the "p" tag is even or odd.
- Is my Array correct for storing the "p" tags?
- How can I use the ternary operator to loop through and automatically set even/odd (I have to use different color backgrounds for evens and odds for read-ability)
this is what I have so far. I know how to manually code the evens/odds in. But I can't seem to find any help the ternary operator to loop through my code and check to see what "p" tags are even or odd.
function paragraph()
{
list = new Array();
var list = document.getElementsByTagName("p");
var even = list[0];
var odd = list[1];
even.style.backgroundColor = "#CCFFFF";
odd.style.backgroundColor = "#CCFFCC";
} //end of paragraph()
I seem to really struggle with arrays and loops. So any help would be greatly appreciated. Thanks in advance.
You actually don't need
list = new Array();becausedocument.getElementsByTagName("p")returns a collection of allptags which you can loop.You need to use
forloop to enumeratelist, then check if the index is odd or even by using(i % 2 > 0)condition and apply the ternary operator as belowPlease note that array index starts from 0, so when
iequals 0, it's odd becauselist[0]is the first element and wheniequals 1, it's even becauselist[1]is the second element, and so on.Working demo: http://jsfiddle.net/6ub3fd7b/