public final void swapTagWithParent ( final Element root , final String selector ) { final Iterable < Element > elements ; // Selected elements Element parent ; // Parent element String text ; // Preserved text checkNotNull ( root , "Received a null pointer as root element" ) ; checkNotNull ( selector , "Received a null pointer as selector" ) ; // Selects and iterates over the elements elements = root . select ( selector ) ; for ( final Element element : elements ) { parent = element . parent ( ) ; // Takes the text out of the element text = element . text ( ) ; element . text ( "" ) ; // Swaps elements parent . replaceWith ( element ) ; element . appendChild ( parent ) ; // Sets the text into what was the parent element parent . text ( text ) ; } }
Finds a set of elements through a CSS selector and swaps its tag with that from its parent .