I can't seem to figure out the strange behavior of the nth-child selector.
After calling the function BackColor1(), my visual appears different than expected:
Something seems off. However, when I call BackColor2(), everything looks normal again.
Could someone please help me understand what went wrong with the BackColor1() function?
Below is the HTML code sample I am working with:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//BackColor1();
//BackColor2();
});
function BackColor1() {
$("li:nth-child(2n+1) > div").css({ "background": "#F2F2F2" });
}
function BackColor2() {
$("li").each(function (key, val) {
if (key % 2 == 0) {
$(this).children("div").css({ "background": "#F2F2F2" });
}
});
}
</script>
</head>
<body>
<ul>
<li>
<div>Video Streaming</div>
<ul>
<li><div>VOD</div></li>
<li><div>Progressive Streaming</div></li>
</ul>
</li>
<li><div>Middle Lesson Without Chapter</div></li>
<li>
<div>File Download</div>
<ul>
<li><div>Direct Download</div></li>
</ul>
</li>
<li><div>Pre Last Lesson Without Chapter</div></li>
<li><div>Last Lesson Without Chapter</div></li>
</ul>
</body>
</html>