Tuesday, February 4, 2014

XPath in Internet Explorer

Every web developer knows how difficult it is to get things running on all browsers. Usually, Internet Explorer is doing the best it can to make your life a hell. A good example thereof, is it's lack of XPath support.

In most browsers, you can use document.evaluate() to pass an XPath expression, and get a result. In Internet Explorer, however, this method just doesn't work. No error message, no result, just some unexpected behavior in your application. Luckily, there's an easy solution that doesn't require you to rewrite your code, or implement some ugly if IE hacks.

The solution is called Wicked Good Xpath, and is an open source project maintained by Google. It's easy to use, and doesn't interfere with your existing code. You can find everything you need here.

Basically, all you have to do is download the .js file, and add it to your page through script tags.

<script src="wgxpath.install.js"></script>

Then you have to call wgxpath.install() from your JavaScript code, and the document.evaluate() function will be available.