[英]jQuery select element by XPath
I have an XPath selector.我有一个 XPath 选择器。 How can I get the elements matching that selector using jQuery?
如何使用 jQuery 获取与该选择器匹配的元素?
I've seen https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript but it doesn't use jQuery, and it seems a little too verbose, and I suppose it's not cross-browser.我看过https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript但它没有使用 jQuery,它似乎有点太冗长,我想它不是跨浏览器的。
Also, this http://jsfiddle.net/CJRmk/ doesn't seem to work.此外,这个http://jsfiddle.net/CJRmk/似乎不起作用。
alert($("//a").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <a href="a1.php"></a> <a href="a2.php"></a>
If you are debugging or similar - In chrome developer tools, you can simply use如果您正在调试或类似 - 在 chrome 开发人员工具中,您可以简单地使用
$x('/html/.//div[@id="text"]')
document.evaluate()
(DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Firefox、Chrome、Safari 和 Opera 支持
document.evaluate()
(DOM Level 3 XPath)——唯一缺少的主要浏览器是 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/ ). 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.
但是,它只是将 XPath 表达式转换为等效的 CSS 选择器。
First create an xpath selector function.首先创建一个xpath选择器function。
function _x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
To use the xpath selector with jquery, you can do like this:要将 xpath 选择器与 jquery 一起使用,您可以这样做:
$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');
Hope this can help.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.