Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: use xpath in jQuery

I have, for example, the next XPath query:

//div[span="something"]/parent::div/child::div[@class=\"someClass\"]

I want to use this XPath query in JavaScript:

return $("a:contains('Fruits')").mouseover();

I tried this:

return $("div[span=\"something\"]/parent::div/child::div[@class=\"someClass\"]").mouseover();

But it didn't work. Is there another semantic for XPath queries in order to use them in JavaScript?

like image 212
Adam Sh Avatar asked Sep 03 '12 07:09

Adam Sh


People also ask

Can you use XPath in jQuery?

The jQuery library supports a basic set of XPath selectors that we can use alongside CSS selectors, if we so desire. And with jQuery, both XPath and CSS selectors can be used regardless of the document type.

Can we use XPath in JavaScript?

This document describes the interface for using XPath in JavaScript internally, in extensions, and from websites. Mozilla implements a fair amount of the DOM 3 XPath, which means that XPath expressions can be run against both HTML and XML documents.

What is custom selector in jQuery?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.


1 Answers

You could add the results of an existing XPath evaluation to a jQuery selection, I threw together this jquery extension that seems does it all for you.

Example usage:

$(document).xpathEvaluate('//body/div').remove()

Here's the add-in.

$.fn.xpathEvaluate = function (xpathExpression) {
   // NOTE: vars not declared local for debug purposes
   $this = this.first(); // Don't make me deal with multiples before coffee

   // Evaluate xpath and retrieve matching nodes
   xpathResult = this[0].evaluate(xpathExpression, this[0], null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

   result = [];
   while (elem = xpathResult.iterateNext()) {
      result.push(elem);
   }

   $result = jQuery([]).pushStack( result );
   return $result;
}
like image 177
Orwellophile Avatar answered Oct 19 '22 22:10

Orwellophile