Jsoup after method doesn't work the way it's expected

Viewed 145

I have a method which has a property description of type "Element" and then I try to add another element using Jsoup.after method.

However, it produces

Exception in thread "main" java.lang.IllegalArgumentException: Object must not be null.

On the other hand, the append method works so well, but I that's not what I really want.

The code is below:

private static void buildTotalvaluesTable2()
{
    Element readyDesc = new Element("p style=\"margin-top:5px\">This is description</p");

    Element totalValuesTable = new Element("table style=\"width:100%; border: 0px; margin-top:20px;\" class=\"hidden\">" +
            "<tbody></tbody>" +
            "</table");

    readyDesc.after(totalValuesTable.outerHtml());

    System.out.println(readyDesc.outerHtml());
}

What I really want to achieve is simply totalValuesTable going after readyDesc.

Can anybody help?

1 Answers

Lets start with explaining what does it mean to set element b as sibling of element a (here represented by a.after(b)).
In short it means placing element b in parent element of element a at position next to (after) a element.

So at this point we can see that main problem with your code is that it doesn't provide any link to parent element in which sibling should be placed.

Simple solution would be to

  1. create Element or Document representing parent,
  2. assign a element as a child of parent element
  3. (only after 1. 2.) assign b element as sibling of a,

In other words something like:

Element parent = new Element("body");

Element a = ...
parent.appendChild(first); // create parent-child relation

Element b = ...
a.after(b);      // now `a` knows about its parent element so it knows 
                 // to which element append `b`

Second problem is that you are not using new Element(...) correctly at

new Element("p style=\"margin-top:5px\">This is description</p");

Purpose of that constructor isn't to create and setup but only create HTML element. Customizing that element should be done later.

In other words don't use new Element("<tag with='attributes'>and other elements</tag>") but new Element("tagName") and set up that element via dedicated methods like:

Element readyDesc = new Element("p");//use only name of tag, without < and >
System.out.println(readyDesc); //raw form: <p></p>

//customize tag
readyDesc.attr("style", "margin-top:5px");
readyDesc.text("This is description");
System.out.println(readyDesc);//customized: <p style="margin-top:5px">This is description</p>
Related