Skip to main content

Element

Struct Element 

Source
pub struct Element<'rewriter, 'input_token, H: HandlerTypes = LocalHandlerTypes> { /* private fields */ }
Expand description

An HTML element rewritable unit.

Exposes API for examination and modification of a parsed HTML element.

Implementations§

Source§

impl<'rewriter, 'input_token, H: HandlerTypes> Element<'rewriter, 'input_token, H>

Source

pub fn tag_name(&self) -> String

Returns the tag name of the element.

Source

pub fn tag_name_preserve_case(&self) -> String

Returns the tag name of the element, preserving its case.

Source

pub fn set_tag_name(&mut self, name: &str) -> Result<(), TagNameError>

Sets the tag name of the element.

The new tag name must be in the same namespace, have the same content model, and be valid in its location. Otherwise change of the tag name may cause the resulting document to be parsed in an unexpected way, out of sync with this library.

Source

pub fn is_self_closing(&self) -> bool

Whether the tag syntactically ends with />. In HTML content this is purely a decorative, unnecessary, and has no effect of any kind.

The /> syntax only affects parsing of elements in foreign content (SVG and MathML). It will never close any HTML tags that aren’t already defined as void in HTML.

This function only reports the parsed syntax, and will not report which elements are actually void in HTML. Use can_have_content() to check if the element is non-void.

If the / is part of an unquoted attribute, it’s not parsed as the self-closing syntax.

Source

pub fn can_have_content(&self) -> bool

Whether the element can have inner content.

Returns true if the element isn’t a void element in HTML, or is in foreign content and doesn’t have a self-closing tag (eg, <svg />).

Note that the self-closing syntax has no effect in HTML content.

Source

pub fn namespace_uri(&self) -> &'static str

Returns the namespace URI of the element.

Source

pub fn attributes(&self) -> &[Attribute<'input_token>]

Returns an immutable collection of element’s attributes.

get_attribute is faster if you only need to read few attributes.

Source

pub fn get_attribute(&self, name: &str) -> Option<String>

Returns the value of an attribute with the name. The value may have HTML/XML entities.

Returns None if the element doesn’t have an attribute with the name.

Source

pub fn has_attribute(&self, name: &str) -> bool

Returns true if the element has an attribute with name.

Source

pub fn set_attribute( &mut self, name: &str, value: &str, ) -> Result<(), AttributeNameError>

Sets value of element’s attribute with name. The value may have HTML/XML entities.

" will be entity-escaped if needed. & won’t be escaped.

If element doesn’t have an attribute with the name, method adds a new attribute to the element with name and value.

Source

pub fn remove_attribute(&mut self, name: &str)

Removes an attribute with the name if it is present.

Source

pub fn before(&mut self, content: &str, content_type: ContentType)

Inserts content before the element.

Consequent calls to the method append content to the previously inserted content.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div id="foo"></div>"#,
    RewriteStrSettings::new().append_element_content_handler(element!("#foo", |el| {
        el.before("<bar>", ContentType::Html);
        el.before("<qux>", ContentType::Html);
        el.before("<quz>", ContentType::Text);

        Ok(())
    }))
).unwrap();

assert_eq!(html, r#"<bar><qux>&lt;quz&gt;<div id="foo"></div>"#);
Source

pub fn streaming_before( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Inserts content from a StreamingHandler before the element.

Consequent calls to the method append to the previously inserted content.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn after(&mut self, content: &str, content_type: ContentType)

Inserts content after the element.

Consequent calls to the method prepend content to the previously inserted content.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div id="foo"></div>"#,
    RewriteStrSettings::new().append_element_content_handler(element!("#foo", |el| {
        el.after("<bar>", ContentType::Html);
        el.after("<qux>", ContentType::Html);
        el.after("<quz>", ContentType::Text);

        Ok(())
    }))
).unwrap();

assert_eq!(html, r#"<div id="foo"></div>&lt;quz&gt;<qux><bar>"#);
Source

pub fn streaming_after( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Inserts content from a StreamingHandler after the element.

Consequent calls to the method prepend to the previously inserted content.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn prepend(&mut self, content: &str, content_type: ContentType)

Prepends content to the element’s inner content, i.e. inserts content right after the element’s start tag.

Consequent calls to the method prepend content to the previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::{ContentType, Element};

let handler = |el: &mut Element| {
    el.prepend("<bar>", ContentType::Html);
    el.prepend("<qux>", ContentType::Html);
    el.prepend("<quz>", ContentType::Text);

    Ok(())
};

let html = rewrite_str(
    r#"<div id="foo"><!-- content --></div><img>"#,
    RewriteStrSettings::new()
        .append_element_content_handler(element!("#foo", handler))
        .append_element_content_handler(element!("img", handler))
).unwrap();

assert_eq!(html, r#"<div id="foo">&lt;quz&gt;<qux><bar><!-- content --></div><img>"#);
Source

pub fn streaming_prepend( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Prepends content from a StreamingHandler to the element’s inner content, i.e. inserts content right after the element’s start tag.

Consequent calls to the method prepend to the previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn append(&mut self, content: &str, content_type: ContentType)

Appends content to the element’s inner content, i.e. inserts content right before the element’s end tag.

Consequent calls to the method append content to the previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::{ContentType, Element};

let handler = |el: &mut Element| {
    el.append("<bar>", ContentType::Html);
    el.append("<qux>", ContentType::Html);
    el.append("<quz>", ContentType::Text);

    Ok(())
};

let html = rewrite_str(
    r#"<div id="foo"><!-- content --></div><img>"#,
    RewriteStrSettings::new()
        .append_element_content_handler(element!("#foo", handler))
        .append_element_content_handler(element!("img", handler))
).unwrap();

assert_eq!(html, r#"<div id="foo"><!-- content --><bar><qux>&lt;quz&gt;</div><img>"#);
Source

pub fn streaming_append( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Appends content from a StreamingHandler to the element’s inner content, i.e. inserts content right before the element’s end tag.

Consequent calls to the method append to the previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn set_inner_content(&mut self, content: &str, content_type: ContentType)

Replaces inner content of the element with content.

Consequent calls to the method overwrite previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::{ContentType, Element};

let handler = |el: &mut Element| {
    el.append("<!-- only one -->", ContentType::Html);
    el.set_inner_content("<!-- will -->", ContentType::Html);
    el.set_inner_content("<!-- survive -->", ContentType::Html);

    Ok(())
};

let html = rewrite_str(
    r#"<div id="foo"><!-- content --></div><img>"#,
    RewriteStrSettings::new()
        .append_element_content_handler(element!("#foo", handler))
        .append_element_content_handler(element!("img", handler))
).unwrap();

assert_eq!(html, r#"<div id="foo"><!-- survive --></div><img>"#);
Source

pub fn streaming_set_inner_content( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Replaces inner content of the element with content from a StreamingHandler.

Consequent calls to the method overwrite previously inserted content. A call to the method doesn’t make any effect if the element is an empty element.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn replace(&mut self, content: &str, content_type: ContentType)

Replaces the element and its inner content with content.

Consequent calls to the method overwrite previously inserted content.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};
use lol_html::html_content::ContentType;

let html = rewrite_str(
    r#"<div id="foo"></div>"#,
    RewriteStrSettings::new().append_element_content_handler(element!("#foo", |el| {
        el.replace("<span></span>", ContentType::Html);
        el.replace("Hello", ContentType::Text);

        Ok(())
    }))
).unwrap();

assert_eq!(html, r#"Hello"#);
Source

pub fn streaming_replace( &mut self, string_writer: Box<dyn StreamingHandler + Send + 'static>, )

Replaces the element and its inner content with content from a StreamingHandler.

Consequent calls to the method overwrite previously inserted content.

Use the streaming! macro to make a StreamingHandler from a closure.

Source

pub fn remove(&mut self)

Removes the element and its inner content.

Source

pub fn remove_and_keep_content(&mut self)

Removes the element, but keeps its content. I.e. remove start and end tags of the element.

§Example
use lol_html::{rewrite_str, element, RewriteStrSettings};

let html = rewrite_str(
    r#"<div><span><!-- 42 --></span></div>"#,
    RewriteStrSettings::new().append_element_content_handler(element!("div", |el| {
        el.remove_and_keep_content();

        Ok(())
    }))
).unwrap();

assert_eq!(html, r#"<span><!-- 42 --></span>"#);
Source

pub fn removed(&self) -> bool

Returns true if the element has been removed or replaced with some content.

Source

pub fn start_tag(&mut self) -> &mut StartTag<'input_token>

Returns the start tag.

Source

pub fn end_tag_handlers( &mut self, ) -> Option<&mut Vec<H::EndTagHandler<'static>>>

Returns the handlers that will run when the end tag is reached.

The handlers may not run if there is no explicit end tag.

You can use this to add your “on end tag” handlers.

This will return None if the element can’t have an end tag.

§Example
use lol_html::html_content::{ContentType, Element};
use lol_html::{element, rewrite_str, text, RewriteStrSettings};
let buffer = std::rc::Rc::new(std::cell::RefCell::new(String::new()));
let html = rewrite_str(
    "<span>Short</span><span><b>13</b> characters</span>",
    RewriteStrSettings::new()
        .append_element_content_handler(element!("span", |el: &mut Element| {
            // Truncate string for each new span.
            buffer.borrow_mut().clear();
            let buffer = buffer.clone();
            if let Some(handlers) = el.end_tag_handlers() {
                handlers.push(Box::new(move |end| {
                    let s = buffer.borrow();
                    if s.len() == 13 {
                        // add text before the end tag
                        end.before("!", ContentType::Text);
                    } else {
                        // replace the end tag with an uppercase version
                        end.remove();
                        let name = end.name().to_uppercase();
                        end.after(&format!("</{}>", name), ContentType::Html);
                    }
                    Ok(())
                }));
            }
            Ok(())
        }))
        .append_element_content_handler(text!("span", |t| {
            // Save the text contents for the end tag handler.
            buffer.borrow_mut().push_str(t.as_str());
            Ok(())
        })),
)
.unwrap();

assert_eq!(html, "<span>Short</SPAN><span><b>13</b> characters!</span>");
Source

pub fn on_end_tag( &mut self, handler: H::EndTagHandler<'static>, ) -> HandlerResult

Adds a handler to run when the end tag is reached. Returns Err when element.can_have_content() is false.

Note: currently end tag handlers are not invoked for implicitly-closed elements.

Use end_tag! macro to provide type hint for the closure’s argument.

§Example
use lol_html::html_content::{ContentType, Element};
use lol_html::{element, end_tag, rewrite_str, text, RewriteStrSettings};
let html = rewrite_str(
    "<span>hi</span>",
    RewriteStrSettings::new().append_element_content_handler(element!(
        "span",
        |el: &mut Element| {
            el.on_end_tag(end_tag!(move |end| {
                end.before("?", ContentType::Text);
                end.after("!", ContentType::Text);
                Ok(())
            }))
        }
    )),
)
.unwrap();

assert_eq!(html, "<span>hi?</span>!");
Source

pub fn source_location(&self) -> SourceLocation

Position of this element’s start tag in the source document, before any rewriting

The end of this element hasn’t been parsed yet. To find it, use Element::end_tag_handlers.

Source

pub fn namespace_uri_c_str(&self) -> &'static CStr

Self::namespace_uri, but as a CStr

Trait Implementations§

Source§

impl<H: HandlerTypes> Debug for Element<'_, '_, H>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl UserData for Element<'_, '_>

Source§

fn user_data(&self) -> &dyn Any

Returns a reference to the attached user data.
Source§

fn user_data_mut(&mut self) -> &mut dyn Any

Returns a mutable reference to the attached user data.
Source§

fn set_user_data(&mut self, data: impl Any)

Attaches user data to a rewritable unit.

Auto Trait Implementations§

§

impl<'rewriter, 'input_token, H> Freeze for Element<'rewriter, 'input_token, H>

§

impl<'rewriter, 'input_token, H = LocalHandlerTypes> !RefUnwindSafe for Element<'rewriter, 'input_token, H>

§

impl<'rewriter, 'input_token, H = LocalHandlerTypes> !Send for Element<'rewriter, 'input_token, H>

§

impl<'rewriter, 'input_token, H = LocalHandlerTypes> !Sync for Element<'rewriter, 'input_token, H>

§

impl<'rewriter, 'input_token, H> Unpin for Element<'rewriter, 'input_token, H>
where <H as HandlerTypes>::EndTagHandler<'static>: Unpin,

§

impl<'rewriter, 'input_token, H> UnsafeUnpin for Element<'rewriter, 'input_token, H>

§

impl<'rewriter, 'input_token, H = LocalHandlerTypes> !UnwindSafe for Element<'rewriter, 'input_token, H>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.