Category Archives: jquery

jQuery in selenium

we all love jQuery. so why not use jQuery in selenium? after all it locates elements. jQuery will make it easy, we just have to add a location strategy that uses jQuery to find elements. These two links helped me get started.

http://stackoverflow.com/questions/2814007/how-do-i-add-a-jquery-locators-to-selenium-remote-control

http://stackoverflow.com/questions/4185640/get-element-with-jquery-and-selenium-ide-1-0-8

Here are the steps i followed. I used selenium-server-standalone-2.2.0.jar downloaded from here.

Step 1:

Extract the jar. I used 7zip to extract.

Step 2:

Edit TestRunner.html inside the core folder.
Add the following as said in SO.

<script language="JavaScript" type="text/javascript" src="jquery.min.js"></script> <script language="JavaScript" type="text/javascript"> function openDomViewer() { var autFrame = document.getElementById('selenium_myiframe');         var autFrameDocument = new SeleniumFrame(autFrame).getDocument();         this.rootDocument = autFrameDocument;         var domViewer = window.open(getDocumentBase(document) + 'domviewer/domviewer.html');         return false; } </script>

And add the jquery-min.js in core folder.

Step 3:

Then add the location strategy to your selenium object as follows.

mySelenium.addLocationStrategy("jquery",
"var loc = locator; " +
"var attr = null; " +
"var isattr = false; " +
"var inx = locator.lastIndexOf('@'); " +


"if (inx != -1){ " +
"   loc = locator.substring(0, inx); " +
"   attr = locator.substring(inx + 1); " +
"   isattr = true; " +
"} " +


"var found = jQuery(inDocument).find(loc); " +
"if (found.length >= 1) { " +
"   if (isattr) { " +
"       return found[0].getAttribute(attr); " +
"   } else { " +
"       return found[0]; " +
"   } " +
"} else { " +
"   return null; " +
"}"
);

Note that this is java code.

Step 4:

Add the following function to user-extensions.js in core/scripts folder.

function jQuery (selector)
{
return selenium.browserbot.getUserWindow().jQuery(selector);
}

Step 5:

Now we need to update the jar file. To do that do something like this.
jar -uf selenium-server-standalone-2.2.0.jar core\TestRunner.html
jar -uf selenium-server-standalone-2.2.0.jar core\jquery.min.js
jar -uf selenium-server-standalone-2.2.0.jar core\scripts\user-extensions.js

Step 6:

That’s it. Just start the server as usual using java -jar selenium-server-standalone-2.2.0

Step 7:

To use jquery to select elements, use something like this.
myselenium.click("jquery=#some_id")

hope it helps.