Intern Logo

Intern‘s Leadfoot API makes it easier to author functional tests in JavaScript. One of the fundamental concepts for authoring functional tests is to access an element within a page to test it.

While most developers are familiar with CSS selectors, this is not always the most efficient mechanism for referencing a particular element in a page.

findByXpath

XPath is a technology that is often overlooked by developers because of the perception that all things XML are overly complex. That said, XPath selectors can be a very powerful and flexible approach for finding an element.

Where findByLinkText only finds links, and findByCssSelector is limited to the capabilities of the CSS engine in the target browser, findByXpath can do much more.

For example, given a simple DOM structure like this:

<dl>
  <dt id="hw">Hello, world</dt>
  <dd>A common greeting</dd>
</dl>

It is possible to find elements in all sorts of different ways:

  • Find the dt element by its text content: findByXpath('//[.="Hello, world"]')
  • Find the parent of the element with id="hw": findByXpath('//[@id="hw"]/..')
  • Find the preceding dt element of the dd element: findByXpath('//dd/preceding-sibling::dt[1]')

These are just some very simple examples of the sorts of complex element selection you can only perform using XPath. The next time you need to find an element with no simple identifier, an XPath selector could be the solution.