Javascript jquery通过xpath选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6453269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:48:08  来源:igfitidea点击:

jquery select element by xpath

javascriptjqueryxpath

提问by Quamis

I have an xpath selector. How can I get the elements matching that selector using jQuery?

我有一个 xpath 选择器。如何使用 jQuery 获取与该选择器匹配的元素?

I've seen https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScriptbut 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>

采纳答案by Wladimir Palant

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.

document.evaluate()Firefox、Chrome、Safari 和 Opera 支持(DOM Level 3 XPath)——唯一缺少的主要浏览器是 MSIE。尽管如此,jQuery 支持基本的 XPath 表达式:http: //docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors(移动到当前 jQuery 版本的插件中,请参阅https://plugins.jquery.com/xpath/) . 然而,它只是将 XPath 表达式转换为等效的 CSS 选择器。

回答by Jeppe Liisberg

If you are debugging or similar - In chrome developer tools, you can simply use

如果您正在调试或类似 - 在 chrome 开发人员工具中,您可以简单地使用

$x('/html/.//div[@id="text"]')

回答by Nanang El Sutra

First create an xpath selector function.

首先创建一个 xpath 选择器函数。

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:

要在 jquery 中使用 xpath 选择器,您可以这样做:

$(_x('/html/.//div[@id="text"]')).attr('id', 'modified-text');

Hope this can help.

希望这能有所帮助。