Given this code:
Element elem = new Element.html("<p>This is a paragraph.</p>");
document.body.append(elem);
document.body.children.add(elem);
document.body.nodes.add(elem);
The results are the same when I add to body.children or to body.nodes. What is the difference between the two? Which is better?
I’ll try to explain it easily.
Let’s assume this HTML snippet:
Now, the thing is that the
childrenproperty comes from theElementclass. It returns a list of otherElementobjects:So, elements can have children who are elements, and so forth.
But then we have the
nodesproperty, which comes from theNodeclass. It returns a list of otherNodeobjects:So, nodes can have child nodes who are nodes themselves too.
The question you should ask is what’s the difference between a node and an element?
Let me add some comments to our previous HTML snippet:
Remember,
ElementextendsNode, which means that<div>and<span>are not only elements, but also nodes! Everything is a node in HTML. In fact, even comments<!-- foo -->are nodes!When you access the
nodesproperty, you will retrieve a list of nodes, basically a list of everything under it, including HTML comments and text.Retriving the
nodesfor the<div>tag above would return oneNode(“hey!”) and oneElement(<span>). However, retrieving thechildrenproperty would only return a list with a singleElement(<span>).So,
nodesliterally contains everything, including elements, text nodes, comments, document types and more.To answer your question now:
These two are the same, the first is just a wrapper for convenience.
When you add to
nodesorchildren, there isn’t really much difference. However, if you retrieve the property, the result can differ. I would generally advise you to usechildrenbecause the results are more what you would expect.Implementation wise, there are little differences as Kyrra mentioned, but nothing too concerning.