Search code examples
javajsouppass-by-reference

Jsoup Element changed by calling appendTo on it


I have a list of Jsoup Element Objects

I loop through them several times and create several new Element Objects from the list.

Something like this:

public static Element mergeElements(List<Element> elements, int startFrom) {
    Element mergedElement = new Element("div");
    for (int i = startFrom; i < elements.size(); i++) {
        elements.get(i).appendTo(mergedElement);
     }
    
    return mergedElement
}

The method above can be called several times, using the same List of element Objects.

I'm observing that the returned mergedElement object is modified after I call mergeElements(). A simplified example.

Element firstMergedElement = mergeElements(elements, 0);
System.out.println(firstMergedElement);
Element secondMergedElement = mergeElements(elements, 1);
// The object has been changed.
System.out.println(firstMergedElement);

Is this possible? Why would appendTo change this?


Solution

  • Method appendTo attaches element to a a new parent. One element can't have two parents at once so in effect elements will be moved from firstMergedElement to secondMergedElement.
    If you want to keep them also in firstMergedElement you can clone each of them:

    elements.get(i).clone().appendTo(mergedElement);
    

    EDIT:
    Additional explanation to show what your code is doing:

    explanation