### Example: Accessing Doctype Data Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Illustrates how to get doctype-specific data from a doctype node. This is used for parsing or validating document types. ```rust if let Some(doctype_data) = node.as_doctype() { println!("Doctype name: {}", doctype_data.name); } ``` -------------------------------- ### Create Attribute Instance Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md Example of creating a simple Attribute instance with no prefix and a string value. Used for initializing attribute data. ```rust let attr = Attribute { prefix: None, value: "example.com".to_string(), }; ``` -------------------------------- ### Example: Accessing Document Data Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Demonstrates how to retrieve document-specific data, such as the quirks mode. This is typically used for top-level document properties. ```rust if let Some(doc_data) = node.as_document() { println!("Quirks mode: {:?}", doc_data.quirks_mode()); } ``` -------------------------------- ### Example: Accessing Text Node Content Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Demonstrates how to retrieve and print the content of a text node. This involves borrowing the RefCell to access the string. ```rust if let Some(text_ref) = node.as_text() { let text = text_ref.borrow(); println!("Text: {}", text); } ``` -------------------------------- ### Example: Inspecting Node Data Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Demonstrates how to inspect the type of node data and print a corresponding message. This is useful for conditional logic based on node type. ```rust match node.data() { NodeData::Element(_) => println!("Element"), NodeData::Text(_) => println!("Text"), NodeData::Comment(_) => println!("Comment"), _ => println!("Other"), } ``` -------------------------------- ### Get Parent Element Reference Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md This example shows how to obtain a reference to the parent node and then attempt to convert it into an element reference (NodeDataRef). ```rust if let Some(parent) = elem_ref.as_node().parent() { if let Some(parent_elem) = parent.into_element_ref() { println!("Parent tag: {:?}", parent_elem.name); } } ``` -------------------------------- ### Example: Accessing Comment Node Content Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Shows how to retrieve and print the content of a comment node. Similar to text nodes, this requires borrowing the RefCell. ```rust if let Some(comment_ref) = node.as_comment() { let text = comment_ref.borrow(); println!("Comment: {}", text); } ``` -------------------------------- ### Configuring Parse Error Callback Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/parser.md Example of setting a custom callback for handling parse errors using `ParseOpts`. ```rust use kuchikiki::ParseOpts; let mut opts = ParseOpts::default(); opts.on_parse_error = Some(Box::new(|err| { eprintln!("Parse error: {}", err); })); ``` -------------------------------- ### Example: Accessing Element Data Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Shows how to safely access element-specific data, such as the tag name. This is used when you know or suspect the node is an element. ```rust if let Some(elem_data) = node.as_element() { println!("Tag: {:?}", elem_data.name); } ``` -------------------------------- ### Parse Error Callback Example Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Demonstrates how to set up a callback function to log non-fatal HTML parse errors. The callback receives an error message string. ```rust use kuchikiki::{parse_html_with_options, ParseOpts}; let mut opts = ParseOpts::default(); opts.on_parse_error = Some(Box::new(|msg| { eprintln!("HTML parse error: {}", msg); })); let parser = parse_html_with_options(opts); let doc = parser.read_to_string(html.into()).unwrap(); ``` -------------------------------- ### Get Default ParseOpts Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Retrieves the default ParseOpts configuration, which uses html5ever's default settings and ignores parse errors. ```rust let opts = ParseOpts::default(); ``` -------------------------------- ### get() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md Retrieves the value of an attribute by its local name in the null namespace. ```APIDOC ## get() ### Description Retrieves the value of an attribute with the given local name (in the null namespace). ### Method `get` ### Parameters #### Path Parameters - **local_name** (A) - Required - The attribute name ### Returns `Option<&str>` - The attribute value, or None if not present ### Example ```rust let attrs = element.attributes.borrow(); if let Some(href) = attrs.get("href") { println!("URL: {}", href); } ``` ``` -------------------------------- ### Create ExpandedName Instance Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md Example of creating an instance of ExpandedName for a specific attribute like 'class'. Requires Namespace and LocalName types. ```rust use html5ever::{Namespace, LocalName}; let name = ExpandedName::new( Namespace::new(None), LocalName::from("class") ); ``` -------------------------------- ### Attributes Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Methods for getting, setting, and removing attributes from HTML elements. ```APIDOC ## Attributes ### `.attributes.get("name")` Get the value of a specific attribute. ### `.attributes.insert("name", "value")` Set or update an attribute with a given name and value. ### `.attributes.remove("name")` Remove a specific attribute. See [Attributes](api-reference/attributes.md) ``` -------------------------------- ### Inclusive Traversal with Node Edges Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Iterates over the start and end edges of a node and its descendants in tree order. Each node appears twice, once for its start edge and once for its end edge. ```rust pub fn traverse_inclusive(&self) -> Traverse ``` ```rust for edge in node.traverse_inclusive() { match edge { NodeEdge::Start(n) => println!("Opening: {:?}", n.data()), NodeEdge::End(n) => println!("Closing: {:?}", n.data()), } } ``` -------------------------------- ### Default HTML Parsing Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Demonstrates parsing HTML using the default configuration, which relies on html5ever defaults and ignores parse errors. ```rust use kuchikiki::parse_html; let parser = parse_html(); let doc = parser.read_to_string(html.into()).unwrap(); ``` -------------------------------- ### Typical HTML Parsing Usage Pattern Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/parser.md Demonstrates the standard workflow for parsing an HTML string into a DOM tree using Kuchiki. ```rust use kuchikiki::traits::* use kuchikiki::parse_html; let html = "

Hello

"; let doc = parse_html().read_to_string(html.into()).unwrap(); // doc is a NodeRef pointing to the document root ``` -------------------------------- ### NodeEdge Enum Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Marks the start or end of a node, used by `Traverse` for entry/exit events. ```rust pub enum NodeEdge { Start(T), End(T), } ``` -------------------------------- ### inclusive_ancestors() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Returns an iterator of this node and its ancestors, starting from this node and moving toward the root. ```APIDOC ## inclusive_ancestors() ### Description Returns an iterator of this node and its ancestors, starting from this node and moving toward the root. ### Method Extension method on `NodeRef` ### Returns `Ancestors` — Iterator yielding NodeRef objects ### Example ```rust for ancestor in node.inclusive_ancestors() { println!("Ancestor: {:?}", ancestor.data()); } ``` ``` -------------------------------- ### Traverse Iterator Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Provides a double-ended iterator over node edges, representing the start and end of each node. ```rust pub struct Traverse(Option>>); impl Iterator for Traverse { } impl DoubleEndedIterator for Traverse { } ``` -------------------------------- ### Kuchikiki Project File Structure Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/INDEX.md Illustrates the directory layout of the Kuchikiki Rust project, including source files and configuration. ```tree kuchikiki/ ├── src/ │ ├── lib.rs (exports) │ ├── tree.rs (NodeRef, Node, NodeData) │ ├── parser.rs (parse_html, ParseOpts) │ ├── select.rs (Selector, Selectors) │ ├── iter.rs (Iterator types) │ ├── attributes.rs (Attributes) │ ├── serializer.rs (serialize) │ ├── node_data_ref.rs (NodeDataRef) │ ├── cell_extras.rs (internal utilities) │ └── tests.rs (tests) └── Cargo.toml ``` -------------------------------- ### Get Element Attributes Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Retrieve attributes from an element. Attributes are accessed via a borrowed `Attributes` map. ```rust let attrs = elem.attributes.borrow(); if let Some(href) = attrs.get("href") { println!("{}", href); } ``` -------------------------------- ### Custom Configuration with Error Collection Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Shows how to create custom ParseOpts and collect all non-fatal parse errors into a vector using a closure and Rc/RefCell. ```rust use kuchikiki::{parse_html_with_options, ParseOpts}; // Collect all parse errors let mut errors = Vec::new(); let mut opts = ParseOpts::default(); let errors_copy = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let errors_ref = errors_copy.clone(); opts.on_parse_error = Some(Box::new(move |msg| { errors_ref.borrow_mut().push(msg.to_string()); })); let parser = parse_html_with_options(opts); let doc = parser.read_to_string(html.into()).unwrap(); // Later, check collected errors let all_errors = errors_copy.borrow(); for error in all_errors.iter() { println!("Parse error: {}", error); } ``` -------------------------------- ### Get Parent Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the parent node of the current node. Returns None if the node is the root. ```rust pub fn parent(&self) -> Option ``` -------------------------------- ### Basic Import Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Import the core `parse_html` function and `NodeRef` type for basic HTML parsing. ```rust // Basic usage use kuchikiki::{parse_html, NodeRef}; ``` -------------------------------- ### Get Node Data Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the node-type-specific data associated with a node. Use this to access the core data of any node. ```rust pub fn data(&self) -> &NodeData ``` -------------------------------- ### Get Last Child Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the last child node of the current node. Returns None if the node has no children. ```rust pub fn last_child(&self) -> Option ``` -------------------------------- ### Entry API for Attribute Manipulation Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md The `entry` method provides an `Entry` API for attributes in the null namespace, enabling conditional insertion or modification. It allows for efficient handling of cases where an attribute might or might not exist. ```rust use indexmap::map::Entry; let mut attrs = element.attributes.borrow_mut(); match attrs.entry("data-value") { Entry::Occupied(mut o) => o.get_mut().value = "new".to_string(), Entry::Vacant(v) => v.insert(Attribute { prefix: None, value: "new".to_string() }), } ``` -------------------------------- ### Get First Child Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the first child node of the current node. Returns None if the node has no children. ```rust pub fn first_child(&self) -> Option ``` -------------------------------- ### Import Specific Types Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Import specific types like `Selectors` and `ParseOpts` for advanced configuration. ```rust // Specific types use kuchikiki::{Selectors, ParseOpts}; ``` -------------------------------- ### Get Selector Specificity Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/selector.md Retrieves the CSS specificity value of a compiled selector. Specificity is used to determine precedence in the cascading algorithm. ```rust pub fn specificity(&self) -> Specificity ``` ```rust let selector = Selector::compile("div#main")?; let spec = selector.specificity(); // Specificity can be compared: spec1 > spec2 ``` -------------------------------- ### Get Next Sibling Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the next sibling node of the current node. Returns None if the node is the last sibling. ```rust pub fn next_sibling(&self) -> Option ``` -------------------------------- ### Kuchikiki Documentation Structure Overview Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md This code block outlines the hierarchical structure of the Kuchikiki documentation, categorizing files into main entry points, reference files, and detailed API references. It helps users understand where to find specific information. ```markdown Main Entry Points: ├── README.md ← Start here for overview ├── INDEX.md ← Navigation guide & quick reference └── 00-START-HERE.md ← This file Reference Files: ├── types.md ← All type definitions ├── configuration.md ← Parser options ├── exported-symbols.md ← Complete symbol inventory └── USAGE-PATTERNS.md ← Real-world code examples API Reference (detailed): └── api-reference/ ├── noderef.md ← Main API (NodeRef) ├── node.md ← Internal structure ├── parser.md ← Parsing functions ├── selector.md ← CSS selectors ├── iterators.md ← Tree traversal ├── attributes.md ← Element attributes ├── serializer.md ← HTML output └── node-data-ref.md ← Type conversion ``` -------------------------------- ### Get Previous Sibling Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Retrieves the previous sibling node of the current node. Returns None if the node is the first sibling. ```rust pub fn previous_sibling(&self) -> Option ``` -------------------------------- ### Rust: Serialize to File (Common Pattern) Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/serializer.md A common pattern for serializing an element to a file named 'output.html'. This uses the `serialize_to_file()` method. ```rust element.serialize_to_file("output.html")?; ``` -------------------------------- ### Tree Navigation Methods Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/MANIFEST.md Methods for navigating the DOM tree structure. ```APIDOC ## parent() ### Description Gets the parent of the current node. ### Method ``` fn parent(&self) -> Option ``` ### Parameters None ### Response - **Option**: An optional reference to the parent node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## first_child() ### Description Gets the first child of the current node. ### Method ``` fn first_child(&self) -> Option ``` ### Parameters None ### Response - **Option**: An optional reference to the first child node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## last_child() ### Description Gets the last child of the current node. ### Method ``` fn last_child(&self) -> Option ``` ### Parameters None ### Response - **Option**: An optional reference to the last child node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## previous_sibling() ### Description Gets the previous sibling of the current node. ### Method ``` fn previous_sibling(&self) -> Option ``` ### Parameters None ### Response - **Option**: An optional reference to the previous sibling node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## next_sibling() ### Description Gets the next sibling of the current node. ### Method ``` fn next_sibling(&self) -> Option ``` ### Parameters None ### Response - **Option**: An optional reference to the next sibling node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` -------------------------------- ### Output HTML Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Convert the document back into an HTML string or serialize it directly to a file. Requires the `Serializer API`. ```rust let html_string = doc.to_string(); doc.serialize_to_file("output.html")?; ``` -------------------------------- ### Parse HTML with Custom Options Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Function signature for parsing a complete HTML document using custom ParseOpts. ```rust pub fn parse_html_with_options(opts: ParseOpts) -> html5ever::Parser ``` -------------------------------- ### Node Creation Methods Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/MANIFEST.md Methods for creating new nodes within the DOM tree. ```APIDOC ## NodeRef::new() ### Description Creates a new node reference. ### Method ``` fn new() -> NodeRef ``` ### Parameters None ### Response - **NodeRef**: A reference to the newly created node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_element() ### Description Creates a new element node reference. ### Method ``` fn new_element(name: ExpandedName) -> NodeRef ``` ### Parameters - **name** (ExpandedName) - Required - The qualified name of the element. ### Response - **NodeRef**: A reference to the newly created element node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_text() ### Description Creates a new text node reference. ### Method ``` fn new_text(data: String) -> NodeRef ``` ### Parameters - **data** (String) - Required - The text content for the node. ### Response - **NodeRef**: A reference to the newly created text node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_comment() ### Description Creates a new comment node reference. ### Method ``` fn new_comment(data: String) -> NodeRef ``` ### Parameters - **data** (String) - Required - The comment content. ### Response - **NodeRef**: A reference to the newly created comment node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_processing_instruction() ### Description Creates a new processing instruction node reference. ### Method ``` fn new_processing_instruction(target: String, data: String) -> NodeRef ``` ### Parameters - **target** (String) - Required - The target of the processing instruction. - **data** (String) - Required - The data for the processing instruction. ### Response - **NodeRef**: A reference to the newly created processing instruction node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_doctype() ### Description Creates a new doctype node reference. ### Method ``` fn new_doctype(name: String, public_id: Option, system_id: Option) -> NodeRef ``` ### Parameters - **name** (String) - Required - The name of the doctype. - **public_id** (Option) - Optional - The public identifier. - **system_id** (Option) - Optional - The system identifier. ### Response - **NodeRef**: A reference to the newly created doctype node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## NodeRef::new_document() ### Description Creates a new document node reference. ### Method ``` fn new_document() -> NodeRef ``` ### Parameters None ### Response - **NodeRef**: A reference to the newly created document node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` -------------------------------- ### Create New Doctype Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/noderef.md Creates a new doctype node with a name, public ID, and system ID. All parameters are converted into Strings. ```rust let doctype = NodeRef::new_doctype("html", "", ""); ``` -------------------------------- ### traverse_inclusive() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Provides an iterator that traverses the node and its descendants, yielding start and end edges for each node. This allows for processing nodes before and after their children are visited. ```APIDOC ## traverse_inclusive() ### Description Returns an iterator of the start and end edges of this node and its descendants in tree order. Each node appears twice: once for `NodeEdge::Start` (before children) and once for `NodeEdge::End` (after children). ### Returns `Traverse` — Iterator of `NodeEdge` values ### Example ```rust for edge in node.traverse_inclusive() { match edge { NodeEdge::Start(n) => println!("Opening: {:?}", n.data()), NodeEdge::End(n) => println!("Closing: {:?}", n.data()), } } ``` ``` -------------------------------- ### Inspect Node Data: Text Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Checks if a node is a text node and returns its content. Use this to get the string value of text nodes. ```rust pub fn as_text(&self) -> Option<&RefCell> ``` -------------------------------- ### Kuchikiki Documentation Output Structure Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/INDEX.md Details the organization of generated documentation files for the Kuchikiki project. ```tree output/ ├── README.md (Overview) ├── INDEX.md (This file) ├── types.md (All type definitions) ├── configuration.md (Parser options) ├── exported-symbols.md (Symbol inventory) ├── USAGE-PATTERNS.md (Code examples) └── api-reference/ ├── noderef.md (Main API) ├── node.md (Internal structure) ├── parser.md (Parsing) ├── selector.md (CSS selectors) ├── iterators.md (Tree traversal) ├── attributes.md (Element data) ├── serializer.md (HTML output) └── node-data-ref.md (Type conversion) ``` -------------------------------- ### Select Descendants by CSS Selector Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Use `select()` to get an iterator of all inclusive descendants matching a CSS selector. Returns an error for invalid selectors. ```rust pub fn select(&self, selectors: &str) -> Result>, ()> ``` ```rust for element in node.select("div.container")? { println!("Found matching div"); } ``` -------------------------------- ### Create New Document Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/noderef.md Creates a new, empty document node. This can be used as the root of an HTML tree. ```rust let doc = NodeRef::new_document(); ``` -------------------------------- ### Node Creation (on NodeRef) Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Methods for creating various types of nodes within the HTML tree structure. ```APIDOC ## Node Creation (on NodeRef) ### `NodeRef::new` Create node from NodeData. ### `NodeRef::new_element` Create element node. ### `NodeRef::new_text` Create text node. ### `NodeRef::new_comment` Create comment node. ### `NodeRef::new_processing_instruction` Create PI node. ### `NodeRef::new_doctype` Create doctype node. ### `NodeRef::new_document` Create document node. ``` -------------------------------- ### Retrieve Attribute Value Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md Use `get` to retrieve the string value of an attribute by its local name in the null namespace. Returns `None` if the attribute is not found. ```rust let attrs = element.attributes.borrow(); if let Some(href) = attrs.get("href") { println!("URL: {}", href); } ``` -------------------------------- ### Access Element Attributes Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md This example shows how to access the attributes map of an element using NodeDataRef and retrieve a specific attribute like 'href'. ```rust let attrs = elem_ref.attributes.borrow(); if let Some(href) = attrs.get("href") { println!("Link: {}", href); } ``` -------------------------------- ### Parse HTML with Default Options Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/parser.md Use this function to parse an HTML document with the default parser configuration. It returns a configured html5ever Parser. ```rust use kuchikiki::parse_html; let parser = parse_html(); let doc = parser.read_to_string(html_string.into()).unwrap(); ``` -------------------------------- ### Node Creation Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Methods for creating new nodes, including elements, text nodes, and comment nodes. ```APIDOC ## Node Creation ### `NodeRef::new_element()` Create a new element node. ### `NodeRef::new_text()` Create a new text node. ### `NodeRef::new_comment()` Create a new comment node. See [NodeRef](api-reference/noderef.md) ``` -------------------------------- ### Get Text Contents of a Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/noderef.md Retrieves all text content from a node and its descendants as a single string. Useful for extracting plain text from HTML or XML structures. ```rust pub fn text_contents(&self) -> String ``` ```rust let text = node.text_contents(); println!("Combined text: {}", text); ``` -------------------------------- ### Get underlying NodeRef with as_node() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Use `as_node()` to retrieve a reference to the underlying NodeRef from a NodeDataRef. This is useful for accessing node methods while retaining the data reference. ```rust pub fn as_node(&self) -> &NodeRef ``` ```rust let parent = elem_ref.as_node().parent(); ``` -------------------------------- ### Tree Navigation (on NodeRef) Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Methods for navigating the HTML tree structure from a given node. ```APIDOC ## Tree Navigation (on NodeRef) ### `parent()` Get parent node. ### `first_child()` Get first child. ### `last_child()` Get last child. ### `previous_sibling()` Get previous sibling. ### `next_sibling()` Get next sibling. ``` -------------------------------- ### entry() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/attributes.md Returns an entry API for an attribute, useful for insert-if-absent operations in the null namespace. ```APIDOC ## entry() ### Description Returns an entry API for the given attribute name (in the null namespace), allowing insert-if-absent patterns. ### Method `entry` ### Parameters #### Path Parameters - **local_name** (A) - Required - The attribute name ### Returns `Entry` - IndexMap entry for manipulation ### Example ```rust use indexmap::map::Entry; let mut attrs = element.attributes.borrow_mut(); match attrs.entry("data-value") { Entry::Occupied(mut o) => o.get_mut().value = "new".to_string(), Entry::Vacant(v) => v.insert(Attribute { prefix: None, value: "new".to_string() }), } ``` ``` -------------------------------- ### new_opt() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Creates a NodeDataRef for a component that may or may not be in a node. This is useful when the component's existence is uncertain. ```APIDOC ## new_opt() ### Description Creates a `NodeDataRef` for a component that may or may not be in a node. ### Signature ```rust pub fn new_opt(rc: NodeRef, f: F) -> Option> where F: FnOnce(&Node) -> Option<&T> ``` ### Parameters #### Path Parameters - **rc** (NodeRef) - Required - The node to keep alive - **f** (F) - Required - Function extracting Option from Node ### Returns - **Option>** - Reference if component exists ### Example ```rust let result = NodeDataRef::new_opt(node, |n| n.as_element()); ``` ``` -------------------------------- ### Clone and Modify HTML Subtree Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/USAGE-PATTERNS.md Demonstrates how to create an independent copy of an HTML subtree using `clone()` and modify it. The cloned subtree can then be detached and manipulated separately before re-insertion. ```rust use kuchikiki::parse_html; use kuchikiki::traits::* fn duplicate_and_modify(html: &str, selector: &str) -> Result> { let doc = parse_html().read_to_string(html.into())?; let original = doc.select_first(selector)?; let cloned = original.as_node().clone(); // Detach and modify cloned.detach(); if let Some(elem) = cloned.as_element() { let mut attrs = elem.attributes.borrow_mut(); attrs.insert("class", "cloned".to_string()); } original.as_node().insert_after(cloned); Ok(doc.to_string()) } ``` -------------------------------- ### Traversal of Descendants with Node Edges Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Iterates over the start and end edges of a node's descendants in tree order, excluding the node itself. Each descendant node appears twice. ```rust pub fn traverse(&self) -> Traverse ``` ```rust for edge in element.traverse() { match edge { NodeEdge::Start(n) => println!("Tag opens"), NodeEdge::End(n) => println!("Tag closes"), } } ``` -------------------------------- ### Get Text Contents of Element Subtree Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Use text_contents() on a NodeDataRef to concatenate all text nodes within an element's subtree. This method returns a String. ```rust pub fn text_contents(&self) -> String // Only on NodeDataRef ``` ```rust let elem_ref: NodeDataRef = ...; let all_text = elem_ref.text_contents(); ``` -------------------------------- ### Tree Navigation Methods Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node.md Methods for navigating the DOM tree structure, available through NodeRef. ```APIDOC ## parent() ### Description Returns the parent node. ### Returns `Option` ### Source `src/tree.rs:340` ``` ```APIDOC ## first_child() ### Description Returns the first child. ### Returns `Option` ### Source `src/tree.rs:346` ``` ```APIDOC ## last_child() ### Description Returns the last child. ### Returns `Option` ### Source `src/tree.rs:352` ``` ```APIDOC ## previous_sibling() ### Description Returns the previous sibling. ### Returns `Option` ### Source `src/tree.rs:358` ``` ```APIDOC ## next_sibling() ### Description Returns the next sibling. ### Returns `Option` ### Source `src/tree.rs:364` ``` -------------------------------- ### traverse() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/iterators.md Returns an iterator that traverses the descendants of a node, yielding start and end edges, excluding the node itself. This is useful for processing the opening and closing of tags within a specific element. ```APIDOC ## traverse() ### Description Returns an iterator of the start and end edges of this node's descendants in tree order, excluding this node. ### Returns `Traverse` — Iterator of `NodeEdge` values for descendants ### Example ```rust for edge in element.traverse() { match edge { NodeEdge::Start(n) => println!("Tag opens"), NodeEdge::End(n) => println!("Tag closes"), } } ``` ``` -------------------------------- ### Serialization Methods Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/MANIFEST.md Methods for serializing the DOM tree into a string or file. ```APIDOC ## serialize() ### Description Serializes the DOM tree into an HTML string. ### Method ``` fn serialize(&self) -> String ``` ### Parameters None ### Response - **String**: The serialized HTML string. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## serialize_to_file() ### Description Serializes the DOM tree to a file. ### Method ``` fn serialize_to_file>(&self, path: P) -> io::Result<()> ``` ### Parameters - **path** (P: AsRef) - Required - The path to the file. ### Response - **io::Result<()**: A result indicating success or an I/O error. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` ```APIDOC ## to_string() ### Description Converts the DOM node to its string representation (implements Display trait). ### Method ``` fn to_string(&self) -> String ``` ### Parameters None ### Response - **String**: The string representation of the node. ### Request Example ```rust // Example usage would go here if provided in source ``` ### Response Example ```json // Example response structure would go here if provided in source ``` ``` -------------------------------- ### Extract Text Contents from an Element Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/README.md Retrieves all the text content within a given element, concatenating text from child nodes. This is a straightforward way to get the human-readable text of an element. ```rust let text = element.text_contents(); ``` -------------------------------- ### Create NodeDataRef with new_opt() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Use `new_opt()` to create a NodeDataRef for a component that might not exist in the node. The projection function returns an Option. ```rust pub fn new_opt(rc: NodeRef, f: F) -> Option> where F: FnOnce(&Node) -> Option<&T> ``` ```rust let result = NodeDataRef::new_opt(node, |n| n.as_element()); ``` -------------------------------- ### Rust: Convert Node to String using Display Trait Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/serializer.md Converts a node and its descendants to an HTML string using the `Display` trait implementation. This is a convenient way to get the HTML representation as a `String`. ```rust let html_string = doc.to_string(); println!("{}", doc); // Also works ``` -------------------------------- ### Alias Import Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Alias the kuchikiki crate to match the original 'kuchiki' naming convention. ```rust // Alias to match original kuchiki use kuchikiki as kuchiki; ``` -------------------------------- ### Display for NodeRef Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/serializer.md Implements the `std::fmt::Display` trait for `NodeRef`, allowing conversion to an HTML string using the `to_string()` method or string formatting macros. This provides a simple way to get the HTML representation of a node. ```APIDOC ## Display Implementation ### Description `NodeRef` implements `std::fmt::Display`, allowing conversion to HTML string using the `to_string()` method or string formatting macros. ### Method `to_string()` or `println!("{}", node)` ### Parameters None ### Returns `String` — The HTML representation of the node. ### Example ```rust // Assuming 'doc' is a NodeRef let html_string = doc.to_string(); println!("{}", doc); // Also works ``` ``` -------------------------------- ### NodeDataRef Creation Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Create and manipulate NodeDataRef instances. ```APIDOC ## NodeDataRef Creation ### Description Create and manipulate NodeDataRef instances. ### Methods - `new()`: Create with projection function. - `new_opt()`: Create with fallible projection. - `as_node()`: Get underlying node. - `text_contents()`: Get text (ElementData only). ### Signature Examples - `(NodeRef, F) -> NodeDataRef` - `(NodeRef, F) -> Option>` - `(&self) -> &NodeRef` - `(&self) -> String` ``` -------------------------------- ### Rust: Serialize Node to File Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/serializer.md Serializes a node and its descendants in HTML syntax to a new file at the specified path. This method handles file creation and writing, returning an `io::Result` to indicate success or failure. ```rust doc.serialize_to_file("/tmp/output.html")?; ``` -------------------------------- ### Selectors String Conversion Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/selector.md Demonstrates parsing a CSS selector string into a `Selectors` object and converting it back to a string. Requires importing `std::str::FromStr` and `kuchikiki::Selectors`. ```rust use std::str::FromStr; use kuchikiki::Selectors; let selectors: Selectors = "div.class, p#text".parse()?; let back_to_string = selectors.to_string(); ``` -------------------------------- ### Create New Comment Node Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/noderef.md Creates a new comment node with the provided text content. The content will be converted into a String. ```rust let comment = NodeRef::new_comment("This is a comment"); ``` -------------------------------- ### Content Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Methods for retrieving text content, serializing the HTML to a string, or writing to a stream. ```APIDOC ## Content ### `.text_contents()` Get all text content from the node and its descendants. ### `.to_string()` Serialize the node and its descendants to an HTML string. ### `.serialize(writer)` Write the serialized HTML of the node and its descendants to a given writer. See [Serializer](api-reference/serializer.md) ``` -------------------------------- ### Create New Element Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/README.md Creates a new HTML element with a specified tag name and attributes. Requires `NodeRef`, `QualName`, `Namespace`, and `LocalName`. ```rust use kuchikiki::NodeRef; use html5ever::{QualName, Namespace, LocalName}; let div = NodeRef::new_element( QualName::new(None, Namespace::new(None), LocalName::from("div")), vec![] ); let text = NodeRef::new_text("Hello"); div.append(text); ``` -------------------------------- ### Node Navigation Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/00-START-HERE.md Methods for navigating the HTML node structure, including accessing parents, children, descendants, and siblings. ```APIDOC ## Node Navigation ### `.parent()` Get parent node. ### `.children()` Iterate over child nodes. ### `.descendants()` Iterate over all descendant nodes. ### `.ancestors()` Iterate over ancestor nodes. ### `.following_siblings()` Iterate over following sibling nodes. See [Iterators](api-reference/iterators.md) ``` -------------------------------- ### Rust: Serialize to Stdout Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/serializer.md Serializes an element to standard output. This requires importing the `std::io` module and uses the `serialize()` method with `io::stdout()` as the writer. ```rust use std::io; element.serialize(&mut io::stdout())?; ``` -------------------------------- ### new() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Creates a NodeDataRef for a component in a given node using a projection function. This is useful when you are certain the component exists. ```APIDOC ## new() ### Description Creates a `NodeDataRef` for a component in a given node using a projection function. ### Signature ```rust pub fn new(rc: NodeRef, f: F) -> NodeDataRef where F: FnOnce(&Node) -> &T ``` ### Parameters #### Path Parameters - **rc** (NodeRef) - Required - The node to keep alive - **f** (F) - Required - Function extracting T from Node ### Returns - **NodeDataRef** - A reference to the component ### Example ```rust let node = NodeRef::new_document(); let doc_ref = NodeDataRef::new(node, |n| n.as_document().unwrap()); ``` ``` -------------------------------- ### as_node() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/node-data-ref.md Returns a reference to the corresponding node. This is useful for accessing the node's methods while still keeping the data reference. ```APIDOC ## as_node() ### Description Returns a reference to the corresponding node. Useful for accessing the node's methods while still keeping the data reference. ### Signature ```rust pub fn as_node(&self) -> &NodeRef ``` ### Returns - **&NodeRef** - Reference to the underlying node ### Example ```rust let parent = elem_ref.as_node().parent(); ``` ``` -------------------------------- ### Element Selection with Selectors Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/selector.md Shows how to use the `select` method from the `ElementIterator` trait to find descendant elements matching a given CSS selector. This requires importing `kuchikiki::traits::*`. ```rust use kuchikiki::traits::*; // Select all divs that match ".active" let active_divs = element .inclusive_descendants() .elements() .select("div.active")?; ``` -------------------------------- ### Define ParseOpts Structure Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Defines the structure for HTML parsing options, including tokenizer, tree builder, and an optional parse error callback. ```rust pub struct ParseOpts { pub tokenizer: html5ever::tokenizer::TokenizerOpts, pub tree_builder: html5ever::tree_builder::TreeBuilderOpts, pub on_parse_error: Option)>>, } impl Default for ParseOpts { } ``` -------------------------------- ### Find Element by Attribute Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/README.md Uses `select_first` to find the first element that matches a specific CSS selector, including attribute selectors. This is efficient for locating a unique or primary element. Requires importing `kuchikiki::traits::*`. ```rust use kuchikiki::traits::*; if let Ok(elem) = root.select_first("input[type='submit']") { println!("Found submit button"); } ``` -------------------------------- ### Serialize Subtree to File Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/USAGE-PATTERNS.md Extracts a specified subtree from an HTML string and serializes it to a file. Requires the `kuchikiki` crate and its `traits` feature. ```rust use kuchikiki::parse_html; use kuchikiki::traits::* fn extract_to_file(html: &str, selector: &str, output_path: &str) -> Result<(), Box> { let doc = parse_html().read_to_string(html.into())?; let element = doc.select_first(selector)?; element.as_node().serialize_to_file(output_path)?; Ok(()) } ``` -------------------------------- ### parse_html_with_options() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/parser.md Parses an HTML document with custom configuration. It returns an html5ever Parser that accepts input via the TendrilSink trait. ```APIDOC ## parse_html_with_options(opts: ParseOpts) ### Description Parses an HTML document with custom configuration. ### Parameters #### Path Parameters - **opts** (ParseOpts) - Required - Custom parser options ### Returns `html5ever::Parser` — A parser configured with the provided options ### Example ```rust use kuchikiki::{parse_html_with_options, ParseOpts}; let opts = ParseOpts::default(); let parser = parse_html_with_options(opts); let doc = parser.read_to_string(html_string.into()).unwrap(); ``` ``` -------------------------------- ### Clone and Modify a Subtree Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/README.md Demonstrates how to clone a subtree, detach it from its original parent, and then append the cloned subtree to a new parent. This is useful for restructuring or duplicating parts of the DOM. ```rust let original = root.descendants().elements().next().unwrap(); let cloned = original.as_node().clone(); cloned.detach(); // Remove from wherever it was parent.append(cloned.as_node().clone()); ``` -------------------------------- ### NodeRef::new_doctype() Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/api-reference/noderef.md Creates a new doctype node with a name, public ID, and system ID. ```APIDOC ## NodeRef::new_doctype() ### Description Creates a new doctype node. ### Method Signature ```rust pub fn new_doctype(name: T1, public_id: T2, system_id: T3) -> NodeRef where T1: Into, T2: Into, T3: Into ``` ### Parameters #### Path Parameters - **name** (T1) - Required - The doctype name - **public_id** (T2) - Required - The public identifier - **system_id** (T3) - Required - The system identifier ### Returns `NodeRef` — A new doctype node ### Example ```rust let doctype = NodeRef::new_doctype("html", "", ""); ``` ``` -------------------------------- ### Serialization (on NodeRef) Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/exported-symbols.md Methods for serializing the HTML tree or parts of it to various outputs. ```APIDOC ## Serialization (on NodeRef) ### `serialize()` Serialize to writer. ### `serialize_to_file()` Serialize to file. ### `to_string()` Serialize to string (Display impl). ``` -------------------------------- ### Parse HTML Fragment with Custom Options Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/configuration.md Function signature for parsing an HTML fragment with custom ParseOpts, requiring context element specification. ```rust pub fn parse_fragment_with_options( opts: ParseOpts, ctx_name: QualName, ctx_attr: Vec ) -> html5ever::Parser ``` -------------------------------- ### Modify HTML and Add Tracking Pixel Source: https://github.com/brave/kuchikiki/blob/main/_autodocs/USAGE-PATTERNS.md Parses HTML, adds a tracking pixel image to the body, and serializes the modified HTML back to a string. Handles cases where the body tag might be missing. Requires 'kuchikiki' and 'html5ever' crates. ```rust use kuchikiki::parse_html; use kuchikiki::traits::* fn add_tracking_pixel(html: &str, pixel_url: &str) -> Result> { let doc = parse_html().read_to_string(html.into())?; // Find the body or create one let body = if let Ok(b) = doc.select_first("body") { b.as_node().clone() } else { let b = kuchikiki::NodeRef::new_element( html5ever::QualName::new(None, ns!(html), local_name!("body")), vec![] ); doc.append(b.clone()); b }; // Add tracking pixel let img = kuchikiki::NodeRef::new_element( html5ever::QualName::new(None, ns!(html), local_name!("img")), vec![] ); if let Some(elem) = img.as_element() { let mut attrs = elem.attributes.borrow_mut(); attrs.insert("src", pixel_url.to_string()); attrs.insert("width", "1".to_string()); attrs.insert("height", "1".to_string()); attrs.insert("alt", "".to_string()); } body.append(img); Ok(doc.to_string()) } ```