while (div.hasChildNodes()) {
fragment.appendChild(div.firstChild)
}
while (div.firstChild) {
fragment.appendChild(div.firstChild)
}
Comparing the two pieces of pseudo code above, they both append each child of div
to fragment
until there are no more children.
- When would you favour
hasChildNodes
orfirstChild
they seem identical. - If the APIs are so similar then why do they both exist. Why does
hasChildNodes()
exist when I can just coercefirstChild
fromnull
tofalse
div.firstChild
be faster because it's a static value as opposed todiv.hasChildNodes()
, which is a lookup function to be called? – Preceptivediv.firstChild
to boolean is faster than the function call overhead, but without measuring, there is no way to definitively know. – Tegularwhile(var fc=div.firstChild) fragment.appendChild(fc)
would another tick faster. – Kimberliekimberlin