Search code examples
javahtmljsoup

retrieve html inline style attribute value with jsoup


Is someone to help me retrieve with jsoup the value of the text-align style in this example ?

<th style="text-align:right">4389</th>

Here i want to get the value right

Thank you!


Solution

  • You can retrieve the style attribute of the element and then split it by :.

    Example:

    final String html = "<th style=\"text-align:right\">4389</th>";
    
    Document doc = Jsoup.parse(html, "", Parser.xmlParser()); // Using the default html parser may remove the style attribute
    Element th = doc.select("th[style]").first();
    
    
    String style = th.attr("style"); // You can put those two lines into one
    String styleValue = style.split(":")[1]; // TODO: Insert a check if a value is set
    
    // Output the results
    System.out.println(th);
    System.out.println(style);
    System.out.println(styleValue);
    

    Output:

    <th style="text-align:right">4389</th>
    text-align:right
    right