Understanding the Priority of the Nodes Returned

Asked 1 years ago, Updated 1 years ago, 124 views

On the Firefox web console

<h1><span class='A'>text1</span>text2</span>text2>/h1>

For the h1 element,

 document.value("span[@class='A']|.", <nodes representing h1 elements >, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerText

called

"Text 1 Text 2"

I got the text.Can I assume that this is because . matches the first node in Document order instead of span[@class='A']?

Also, can a single XPath be used to prioritize nodes that match xpath1 regardless of the document order and return nodes that match xpath2 if no such node exists?
(As mentioned above, xpath1|xpath2 was not enough.I will return the set, so it is only natural.)

javascript xpath

2022-09-30 21:27

2 Answers

I wonder if it's like this.

'use strict';
/**
 * Get the first matching h1 element node (context node)
 */
var h1 = document.value("span[@class='A']|.", document.querySelector('h1'), null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(h1);//<h1><span class='A'>text1</span>text2</span>/h1>

/**
 * Obtain element nodes except root nodes (context nodes)
 */
varspan=document.value("span[@class='A']|descendant::*", document.querySelector('h1'), null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
console.log(span);//<span class='A'>text1</span>

/**
 * If it does not match span [@class='A'],
 */
var node=document.value("span[@class='A']", document.querySelector('h1'), null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

if(!node){
  node = document.evaluate("."", document.querySelector('h1'), null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

console.log(node);//<span class='A'>text1</span>
<h1><span class='A'>text1</span>text2</span>text2>/h1>


2022-09-30 21:27

What about xpath1|xpath2[not(xpath1)]?

(In XPath 2.0 and later, xpath1, xpath2 are both single nodes, although (xpath1,xpath2)[1] is standard.)


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.