XPathEvaluator: createExpression() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Phương thức này biên dịch một XPathExpression có thể được sử dụng để đánh giá (lặp lại) biểu thức XPath.

Cú pháp

js
createExpression(expression)
createExpression(expression, resolver)

Tham số

expression

Chuỗi biểu diễn biểu thức XPath cần được tạo.

resolver Optional

Một Node, null, hoặc bất kỳ đối tượng nào triển khai phương thức lookupNamespaceURI. Cho phép dịch tất cả các tiền tố, bao gồm cả tiền tố không gian tên xml, trong biểu thức XPath sang các URI không gian tên thích hợp.

Giá trị trả về

Một XPathExpression biểu diễn dạng đã biên dịch của biểu thức XPath.

Ngoại lệ

INVALID_EXPRESSION_ERR

Nếu biểu thức không hợp lệ theo các quy tắc của XPathEvaluator, một DOMException loại INVALID_EXPRESSION_ERR sẽ được ném ra.

NAMESPACE_ERR

Nếu biểu thức chứa các tiền tố không gian tên không thể được giải quyết bởi XPathNSResolver được chỉ định, một DOMException loại NAMESPACE_ERROR sẽ được ném ra.

Ví dụ

Ví dụ sau đây cho thấy cách sử dụng phương thức evaluate().

HTML

html
<div>XPath example</div>
<div>Number of &lt;div&gt;s: <output></output></div>

JavaScript

js
const xpath = "//div";
const evaluator = new XPathEvaluator();
const expression = evaluator.createExpression(xpath);
const result = expression.evaluate(
  document,
  XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
);
document.querySelector("output").textContent = result.snapshotLength;

Kết quả

Thông số kỹ thuật

Thông số kỹ thuật
DOM
# dom-xpathevaluatorbase-createexpression

Tương thích trình duyệt

Xem thêm