html5ever icon indicating copy to clipboard operation
html5ever copied to clipboard

Replacing NodeRef with it's child

Open ArmenAg opened this issue 4 years ago • 0 comments

I'm working on a project that requires manipulating DOM to simplify HTML. One example of a transform is removing all nested <div> to the innermost <div> element.

My first attempt was to do the following

impl Filter for CollapseTwoConsecutiveDivElementsFilter {
    fn filter(&self, node: NodeRef) -> bool {
        let mut g_has_mutated = false;
        if CollapseTwoConsecutiveDivElementsFilter::is_div_element(&node)
            && node.children().count() == 1
        {
            if CollapseTwoConsecutiveDivElementsFilter::is_div_element(&node.first_child().unwrap())
            {
                node.first_child().unwrap().insert_before(node.clone());
                node.clone().detach();
                g_has_mutated = true;
            }
        }
        for child in node.clone().borrow_mut().children() {
            g_has_mutated |= self.filter(child.clone());
        }

        return g_has_mutated;
    }
}

but I quickly realized I'm not augmenting node, therefore i get the wrong behavior. I saw implemented internally of Node there was a .replace function. Is it possible to do replace current NodeRef with it's direct child?

ArmenAg avatar Feb 02 '21 09:02 ArmenAg