Search code examples
javaxpathhtmlunit

How to get an element under a display:none div using htmlunit


Using HtmlUnit, How should I grab an element that is under a hidden div (style= "display:none")?

In this case, I am trying to get the value of a field presented in a table. the first cell is the field name and the second one is the value. I am using "for" attribute to find the associated value.

HTML:

<div style="display: none;" id="tab-doc-div">
<div class="tab-container" align="center">
    <table class="datatable">
        <tbody>
            <tr>
                <th rowspan="1" colspan="1">
                    &nbsp;<label for="doc.change.stat">
                    <font color="">*&nbsp;</font>Action</label>
                </th>
                <td colspan="2">
                    Data Change (DTA)
                </td>
            </tr>
        </tbody>
    </table>
</div>

Java/HtmlUnit Code I'm using:

public static String getTextForProperty(HtmlPage page, String property) throws Exception {
    List<HtmlLabel> labels = (List<HtmlLabel>)page.getByXPath("//label[@for='" + property + "']");

    if (labels.isEmpty()) {
        return null;
    } else {
        return labels.get(0).getParentNode().getNextSibling().asText();
    }
}
String myValue = getTextForProperty(myPageObject, "doc.change.stat"); //returns null

Solution

  • Given your sample HTML file and your comment on the other answer:

    In my example I want to get the "Data Change (DTA)" as the result

    This is all you need:

    HtmlTableCell td = page.<HtmlTableCell>
                         getFirstByXPath("//label[@for='doc.change.stat']/../../td");
    System.out.println(td.getTextContent().trim());