XPath Checker

How to check elements of a given CSS class?

It is often necessary to count elements on a given component. This could be the number of results on a search page or the number of teasers on an editorial homepage. In most cases, those elements are defined as HTML classes.

If it is only necessary to check whether an element exists or not the easiest way is to use the CSS selector check. There you just have to enter the class name (e.g. #teaserElement). If the number is important the best solution is the XPath checker, where a simple query looks like:

XPath: //div[contains(@class, "teaserElement")]

This query looks for an HTML div element that contains the class teaserElement. If the element is not a div container just use section or figure or whatever the element is declared as.

Checking XPath using Google Chrome

While xpaths can be very complex there is an easy way to validate them against a given website using chrome. The first thing you have to do is opening the development tools (Ctrl + Shift + I). Then go to “Console”. Here you are able to interact with your website using javascript.

Chrome offers a special Javascript function to all its users. It’s $x(). With this function you can apply an XPath to the current website. That means if you enter the function into the console the browser will execute the function and return the elements that where found.

$x("//html/head/meta[@property='og:title']");

This XPath checks if a html meta tag with the property og:title exists.

Difference between XML/HTML and DOM

When using the XPath checker it is possible to choose between two options: XML/HTML or DOM. The DOM option is important when Leankoala should check for an XPath within an HTML page. There are two states of such a page. The first is the HTML file. It is the content a web browser sends to a client. No JavaScript was executed, that could enrich or change the content. Those sources are very robust as they cannot be changed by a third party component. 

The next stage is the document object model (DOM). The browser has loaded all elements and has executed the JavaScript functions. When there are ads on a page they can produce a lot of changes in the DOM and can sometimes also break the syntax. Browsers can repair a lot but not everything. 

For static elements like a title tag, canonical tags or even a critical CSS element, we recommend using the HTML check. When important elements are rendered on run-time use the DOM check.

Table of contents