How to get HTML code of a WebElement in Selenium

LoveLovelyJava picture LoveLovelyJava · Aug 26, 2015 · Viewed 50.7k times · Source

I am new at testing so my apologies in advance if my question sounds a bit primary.

I am using Selenium and Java to write a test.

I know that webElement.getAttribute("innerHTML"); brings me the innerHTML, for example for the element below:

<a href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button" style="position: absolute; border-radius: 0px 0px 4px 4px;">
    <span class="ui-icon ui-icon-closethick">close</span>
</a>

it returns:

<span class="ui-icon ui-icon-closethick">close</span>

but I need something that brings me the inner attribute of WebElement "a", something like below:

href="#" class="ui-dialog-titlebar-close ui-corner-all" role="button" style="position: absolute; border-radius: 0px 0px 4px 4px;"

Answer

JeffC picture JeffC · Aug 27, 2015

If you want the HTML of the element itself, you can use

webElement.getAttribute("outerHTML");

It will return the HTML of the element itself plus all the children elements. I'm not sure if that's exactly what you want. I don't think there is a way to just get the HTML of the selected element only.