File tree Expand file tree Collapse file tree 3 files changed +30
-10
lines changed Expand file tree Collapse file tree 3 files changed +30
-10
lines changed Original file line number Diff line number Diff line change 2
2
3
3
All notable changes to the ` dom_query ` crate will be documented in this file.
4
4
5
+ ## [ Unreleased]
6
+
7
+ ### Fixed
8
+
9
+ - Fixed the behavior of ` NodeRef::to_fragment ` when the node is an html element or the root itself.
10
+
5
11
## [ 0.19.0] - 2025-05-20
6
12
7
13
### Added
Original file line number Diff line number Diff line change @@ -747,23 +747,30 @@ impl NodeRef<'_> {
747
747
748
748
/// Creates a full copy of the node's contents as a [Document] fragment.
749
749
pub fn to_fragment ( & self ) -> Document {
750
- let fragment = Document :: fragment_sink ( ) ;
751
750
752
- let fragment_root_id = fragment. tree . root ( ) . id ;
753
- fragment. tree . new_element ( "body" ) ;
751
+ if self . id . value == 0 || self . has_name ( "html" ) {
752
+ return Document {
753
+ tree : self . tree . clone ( ) ,
754
+ ..Default :: default ( )
755
+ } ;
756
+ }
757
+
758
+ let frag = Document :: fragment_sink ( ) ;
759
+ let f_tree = & frag. tree ;
760
+ let f_root_id = f_tree. root ( ) . id ;
761
+
762
+ f_tree. new_element ( "body" ) ;
754
763
755
- let html_node = fragment. tree . new_element ( "html" ) ;
756
- fragment
757
- . tree
758
- . append_child_of ( & fragment_root_id, & html_node. id ) ;
764
+ let html_node = f_tree. new_element ( "html" ) ;
765
+ f_tree. append_child_of ( & f_root_id, & html_node. id ) ;
759
766
760
767
{
761
- let new_child_id = fragment . tree . copy_node ( self ) ;
762
- let mut fragment_nodes = fragment . tree . nodes . borrow_mut ( ) ;
768
+ let new_child_id = f_tree . copy_node ( self ) ;
769
+ let mut fragment_nodes = f_tree . nodes . borrow_mut ( ) ;
763
770
TreeNodeOps :: append_children_of ( & mut fragment_nodes, & html_node. id , & new_child_id) ;
764
771
}
765
772
766
- fragment
773
+ frag
767
774
}
768
775
}
769
776
Original file line number Diff line number Diff line change @@ -579,5 +579,12 @@ fn test_copy_fragment() {
579
579
dst_node. children_it( false ) . count( )
580
580
) ;
581
581
582
+ let frag = src_frag. root ( ) . to_fragment ( ) ;
583
+ assert_eq ! ( frag. select( "html" ) . length( ) , 1 ) ;
584
+
585
+ let frag = src_frag. html_root ( ) . to_fragment ( ) ;
586
+ assert_eq ! ( frag. select( "html" ) . length( ) , 1 ) ;
587
+
588
+
582
589
assert ! ( dst_frag. tree. validate( ) . is_ok( ) ) ;
583
590
}
You can’t perform that action at this time.
0 commit comments