JSoup Remove Elements

akshayb picture akshayb · May 8, 2013 · Viewed 25.4k times · Source

Even though, this may sound too basic, I would like to ask how do I remove an element from doc using Jsoup.

I tried searching for it, but no success.

Here is problem:

Elements myNewElements = doc.getElementsByAttribute("hello");

//Now I need to perform some other methods on myNewElements before removing.
//Hence..suggested method says,
doc.getElementsByAttribute("hello").remove();

This works fine. But I believe selecting same elements again and again could prove memory hungry. Is it possible ?

doc.select(myNewElements).remove();

//Try to select myNewElements from doc.

Answer

Francisco Paulo picture Francisco Paulo · May 8, 2013

If you didn't add any new elements that match your inital select, you don't need to select the elements again.

Each element in elements has a reference to its parent and the remove() method just tells the parent to remove that child element.

In essence, just doing:

myNewElements.remove()

should work.