This isn't exactly a problem in the code, but I cannot understand the reason behind my problem. First, please have a look at the code:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Head First : Javascript</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
<script type="text/javascript" src="cookie.js"></script>
</head>
<body>
<div id="row1">
<p>False</p>
<p>False</p>
<p>True</p>
<p>True</p>
<p>False</p>
</div>
<div id="row2">
<p>False</p>
<p>False</p>
<p>True</p>
<p>False</p>
<p>False</p>
</div>
<div id="row3">
<p>False</p>
<p>True</p>
<p>True</p>
<p>True</p>
<p>True</p>
</div>
<div id="row4">
<p>True</p>
<p>False</p>
<p>False</p>
<p>True</p>
<p>False</p>
</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
CSS:
p{
display:inline-block;
width:50px;
margin:30px;
text-align:center;
}
JS:
function setElementColor(){
var numberRows = parseInt(window.prompt("Enter total number of rows that you are seeing on the screen."));
for(var i = 1; i <= numberRows; i++){
var firstElement = document.getElementById('row' + i).firstElementChild;
var counterElement;
//For now, total elements in 1 row = 5
for(var q = 1; q <= 5; q++){
if(q == 1){
firstElement.style.backgroundColor = "red";
counterElement = firstElement.nextSibling;
}
else{
counterElement.style.backgroundColor = "green";
}
counterElement = counterElement.nextElementSibling;
}
}
}
setElementColor();
Now, this might be a stupid question, but it will make sense (I believe). The code that you are seeing is correct, and works without a doubt. But, can you see that nextSibling
property in the first if
statement? That is what is confusing me.
Now, all paragraphs have spaces between each other, so this means that all browsers will see those spaces as textNode
(except IE). Now, by the means of logic, there should have been a nextElementSibling
property there, so that the code looks forward for the next Element, ignoring comments/textNodes, but I tried it, and that is not working.
Can someone give me a satisfying reasoning behind that?