Exercise 3: Two Sibling Paragraphs — Possible Solution ==================================================================== THE TEST ------------------------------ html = "

One

Two

" builder = TinyDOMBuilder() builder.feed(html) print(builder.root) HAND SKETCH (before running) ------------------------------ #document div p "One" p "Two" Both

elements should sit at the SAME indentation level, as two separate children of the one div -- not nested inside each other, since the source closes each

(

) before the next one opens. ACTUAL VERIFIED OUTPUT ------------------------------ Element('#document') Element('div') Element('p') Text('One') Element('p') Text('Two') Matches the hand sketch exactly. WHY THIS WORKS AS AN ANSWER ------------------------------ TinyDOMBuilder's own handle_endtag pops the stack the moment a closing tag is seen -- so by the time the parser reaches the second

, the first one has already been popped back off, leaving div (not the first p) as the current top of the stack. The second p therefore gets appended as div's own child, at the same level as the first p, rather than being nested inside it. This is the exact mechanism that makes "next to" and "nested inside" genuinely different outcomes in a real DOM tree: it isn't about how the two elements LOOK when written next to each other in the source -- it's about whether a closing tag was seen (popping back up a level) before the next opening tag arrived. Two sibling

elements close cleanly before the next one starts; two NESTED elements (like this chapter's own

... example) don't close until after the inner one has already opened, which is exactly why the stack-based approach handles both cases correctly without needing any special-casing for either shape.