Nested search queries document.evalute?

var links = document.evaluate("//BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).evaluate("//A"); 

Basically, I need to find the element through xpath. then search for this item through xpath. The above does not work explicitly, but does not use the contextNode argument.

 var headings = document.evaluate("//BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1]", document, null, XPathResult.ANY_TYPE, null); var thisHeading = headings.iterateNext(); var headings2 = document.evaluate("//A", thisHeading, null, XPathResult.ANY_TYPE, null); headings2.iterateNext().style.backgroundColor = "red"; 

I need to be able to search for child elements of an element through xpath.

+4
source share
3 answers

You must use XPathResult.FIRST_ORDERED_NODE_TYPE in combination with singleNodeValue to get the first element of an XPath expression. Then use .//A to select any <a> element that is a child of the consistent node. If you want to combine a straight child, use ./A :

 var headings = document.evaluate("//BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); var thisHeading = headings.singleNodeValue; var headings2 = document.evaluate(".//A", thisHeading, null, XPathResult.ANY_TYPE, null); headings2.iterateNext().style.backgroundColor = "red"; 
+2
source

The problem is that p tag child elements must be inline elements. Tables in paragraphs are not allowed. If you remove the p tags, you can use your source code, see This jsfiddle .

+2
source

Basically, I need to find the element through xpath. then search for the item via xpath

This can be accomplished with a single XPath expression.

Using

 //BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1]//A 

To select all elements //BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1] that do not have a child A , use :

 //BODY/CENTER[1]/P[1]/TABLE[1]/TBODY[1]/TR[1][not(//A)] 
+1
source

Source: https://habr.com/ru/post/1380991/


All Articles