akshayb
akshayb

Reputation: 1239

JSoup Remove Elements

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.

Upvotes: 18

Views: 33101

Answers (2)

user2363488
user2363488

Reputation:

Better loop over the elements and remove them within:

for( Element element : doc.select(myNewElements) )
{
    element.remove();
}

There's a similar question: Parse html with jsoup and remove the tag block

Upvotes: 1

Francisco Paulo
Francisco Paulo

Reputation: 6322

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.

Upvotes: 31

Related Questions