jquery xpath code example
Example 1: get element by xpath
document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Example 2: what is xpath
How many types of xpath are there?
- Two types of xpath
-> What are the two types?
- Absolute and Relative xpath
#1- Absolute xpath:
- starts with /
- Starts from the very beginning of the html page,
and goes down to desired web element 1 by 1.
- it is NOT dependable at all.
- easly brakes if there is any minimal changes
in the structure of the HTML page.
#2- Relative xpath:
- starts with //
- // means you can start from anywhere in the HTML code
- it will jump to the first matching value and return it
- There are MANY different options to use relative xpath
Commmon xpaths:
#1- //tagName[@attribute='value']
#2- //*[@attribute='value'] --> * means look for all web elements
#3- //tagName[.='text'] --> returns the web element with given text.
-> instead of giving tag name if you pass * it return all the web elements
that contain given attribute and value regardless of the tag name.
Example 3: jquery xpath
document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.