I am trying to understand a code I found on the internet. I dont't understand in the while loop, why it is not an infinite loop. If change the calculator.appendChild
in it to e.g. console.log
it runs forever.
window.location.hash = 1;
var calculator = document.createElement("div");
calculator.id = "height-calculator";
while (document.body.firstChild) {
calculator.appendChild(document.body.firstChild);
}
document.body.appendChild(calculator);
document.title = calculator.clientHeight;
Basically there is always a first child in a non-empty site, so the condition is always true. Can someone explain why this way it doesn't run forever?
click Chrome DevTools window to get focus on it, pause script with F8, Ctrl+\ or by clicking Pause script execution button, press mouse button for 1-3 seconds on the button again to see more options, move click action to square stop button on expanded menu to stop permanently script execution.
Infinite while Loop You can also use the true built-in or any other statement that always returns true. The while loop above will run indefinitely. You can terminate the loop by pressing CTRL+C .
An infinite loop will run forever, but the program can be terminated with the break keyword. In the below example, we will add an if statement to the while loop, and when that condition is met, we will terminate the loop with break .
A element can only be child of one other element.
calculator.appendChild(document.body.firstChild);
As soon as you attach document.body.firstChild
to your calculator, it automatically detaches from body, so body will eventually run out of children.
So process happens in 3 simple steps:
var calculator = document.createElement("div");
this line creates a div
OUTSIDE of the body
in the DOM
Then the loop moves all the children of body
into the calculator
which eventually ends unless body
has infinite children which is not possible.
document.body.appendChild(calculator);
moves the calculator
under body
So basically there are two major entities body
and calculator
, script moves all the children of body
to calculator
and then it moves calculator
to body
.
In other words script converts all children of body
to the grandchildren
of body
and the only child of body
becomes the calculator
I know I wrote too much but I myself understood it after a while, reading other comments and answers so I just wanted to leave it here for myself for future and for anyone else who needs more explanation to get it LOL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With