We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

ParentNode

I heard you like recursion.

Our new ParentNode class will handle the nesting of HTML nodes inside of one another. Any HTML node that's not "leaf" node (i.e. it has children) is a "parent" node.

Assignment

    • The tag and children arguments are not optional
    • It doesn't take a value argument
    • props is optional
    • (It's the exact opposite of the LeafNode class)

You can iterate over all the children and call to_html on each, concatenating the results and injecting them between the opening and closing tags of the parent.

For example, this node and its children:

node = ParentNode(
    "p",
    [
        LeafNode("b", "Bold text"),
        LeafNode(None, "Normal text"),
        LeafNode("i", "italic text"),
        LeafNode(None, "Normal text"),
    ],
)

node.to_html()

Should convert to:

<p><b>Bold text</b>Normal text<i>italic text</i>Normal text</p>

Don't worry about indentation or pretty-printing. If pretty-printed it would look like this:

<p>
  <b>Bold text</b>
  Normal text
  <i>italic text</i>
  Normal text
</p>

Most editors are easily configured to auto-format HTML on save, so we won't worry about implementing that in our code.

def test_to_html_with_children(self):
    child_node = LeafNode("span", "child")
    parent_node = ParentNode("div", [child_node])
    self.assertEqual(parent_node.to_html(), "<div><span>child</span></div>")


def test_to_html_with_grandchildren(self):
    grandchild_node = LeafNode("b", "grandchild")
    child_node = ParentNode("span", [grandchild_node])
    parent_node = ParentNode("div", [child_node])
    self.assertEqual(
        parent_node.to_html(),
        "<div><span><b>grandchild</b></span></div>",
    )

Run and submit the CLI tests from the root of the project.