pub struct Element<'r, 't> { /* private fields */ }
Expand description

An HTML element rewritable unit.

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

Implementations§

source§

impl<'r, 't> Element<'r, 't>

source

pub fn tag_name(&self) -> String

Returns the tag name of the element.

source

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

Sets the tag name of the element.

source

pub fn is_self_closing(&self) -> bool

Whether the element is explicitly self-closing, e.g. <foo />.

source

pub fn can_have_content(&self) -> bool

Whether the element can have inner content. Returns true unless the element is an HTML void element or has a self-closing tag (eg, <foo />).

source

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

Returns the namespace URI of the element.

source

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

Returns an immutable collection of element’s attributes.

source

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

Returns the value of an attribute with the name.

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.

If element doesn’t have an attribute with the name, method adds 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 {
        element_content_handlers: vec![
            element!("#foo", |el| {
                el.before("<bar>", ContentType::Html);
                el.before("<qux>", ContentType::Html);
                el.before("<quz>", ContentType::Text);

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<bar><qux>&lt;quz&gt;<div id="foo"></div>"#);
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 {
        element_content_handlers: vec![
            element!("#foo", |el| {
                el.after("<bar>", ContentType::Html);
                el.after("<qux>", ContentType::Html);
                el.after("<quz>", ContentType::Text);

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div id="foo"></div>&lt;quz&gt;<qux><bar>"#);
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 {
        element_content_handlers: vec![
            element!("#foo", handler),
            element!("img", handler),
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div id="foo">&lt;quz&gt;<qux><bar><!-- content --></div><img>"#);
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 {
        element_content_handlers: vec![
            element!("#foo", handler),
            element!("img", handler),
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div id="foo"><!-- content --><bar><qux>&lt;quz&gt;</div><img>"#);
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 {
        element_content_handlers: vec![
            element!("#foo", handler),
            element!("img", handler),
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"<div id="foo"><!-- survive --></div><img>"#);
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 {
        element_content_handlers: vec![
            element!("#foo", |el| {
                el.replace("<span></span>", ContentType::Html);
                el.replace("Hello", ContentType::Text);

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).unwrap();

assert_eq!(html, r#"Hello"#);
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 {
        element_content_handlers: vec![
            element!("div", |el| {
                el.remove_and_keep_content();

                Ok(())
            })
        ],
        ..RewriteStrSettings::default()
    }
).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<'t>

Returns the start tag.

source

pub fn on_end_tag( &mut self, handler: impl FnOnce(&mut EndTag<'_>) -> Result<(), Box<dyn Error + Send + Sync>> + 'static ) -> Result<(), EndTagError>

Sets a handler to run when the end tag is reached.

Subsequent calls to the method on the same element replace the previous handler.

Example
use lol_html::html_content::ContentType;
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 {
        element_content_handlers: vec![
            element!("span", |el| {
                // Truncate string for each new span.
                buffer.borrow_mut().clear();
                let buffer = buffer.clone();
                el.on_end_tag(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(())
            }),
            text!("span", |t| {
                // Save the text contents for the end tag handler.
                buffer.borrow_mut().push_str(t.as_str());
                Ok(())
            }),
        ],
        ..RewriteStrSettings::default()
    },
)
.unwrap();

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

Trait Implementations§

source§

impl Debug for Element<'_, '_>

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<'r, 't> !RefUnwindSafe for Element<'r, 't>

§

impl<'r, 't> !Send for Element<'r, 't>

§

impl<'r, 't> !Sync for Element<'r, 't>

§

impl<'r, 't> Unpin for Element<'r, 't>where 't: 'r,

§

impl<'r, 't> !UnwindSafe for Element<'r, 't>

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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 Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.