How to get innerHTML or attributes of an element?

UI-licious currently does not have built-in commands to read the HTML or attributes of an element into the test script.

However there are workarounds using the UI.execute command. The UI.execute command executes javascript within the browser’s execution context, and any values returned from the javascript function executed will be passed to the context of the text script.

Get HTML from an element

We can create a helper function to extract the HTML of an element as such:

function I_getHTML(cssSelector){
  return UI.execute(function(cssSelector){
    // this code executes on the browser side
    var element = document.querySelector(cssSelector)
    if(element){
      return element.innerHTML
    }
    return null 
  }, [cssSelector])
}

This method is designed to work for CSS selectors, but you can also modify it to process XPATH selectors by using document.evaluate instead of document.querySelector to query the element.

You can then use the I_getHTML function in your test script as such:

I.goTo("https://github.com/login")

// how to get HTML from an element
var calloutHTML = I_getHTML(".login-callout")
TEST.log.info(".login-callout HTML is: " + calloutHTML)

Get all attributes of an element

Similarly, we can create a helper function to extract all attributes of an element, as such:

function I_getAttributes(cssSelector){
  return UI.execute(function(cssSelector){
    // this code executes on the browser side
    var element = document.querySelector(cssSelector)
    if(element){
      var attributes = {}
        for(var i = 0; i < element.attributes.length; i++){
          var attr = element.attributes[i]
          attributes[attr.localName] = attr.value
        }
        return attributes
      }
      return null 
  }, [cssSelector])
}

We can tend use it in our test script like this:

I.goTo("https://github.com/login"

// how to get attributes from an element
var loginFieldAttributes = I_getAttributes("#login_field")
TEST.log.info("#login_field attributes are: " + JSON.stringify(loginFieldAttributes))

Full example

Here’s a full example based on Github’s login form: