简体   繁体   English

DOM 通过 Xpath 查找元素

[英]DOM find element by Xpath

I'm new to DOM querying and I'm wondering if it is possible to query DOM elements directly by Xpath in a similar way to the below-mentioned code?我是 DOM 查询的新手,我想知道是否可以通过 Xpath 以类似于下面提到的代码的方式直接查询 DOM 元素?

document.getElementById("searchInput");

Thanks!谢谢!

The equivalent statement using only XPath would be 仅使用XPath的等效语句为

xPathResult = document.evaluate('//*[@id="searchInput"]', document);
if(xPathResult){
     element = xPathResult.iterateNext();
}

Have a look at the Intro to XPath in the browser on MDN for some more examples and usages. 在MDN的浏览器中查看XPath简介,以获取更多示例和用法。

If you're looking for one or the first element behind your XPath, you can use this one liner:如果你正在寻找 XPath 后面的一个或第一个元素,你可以使用这个衬垫:

const yourstring = "/html/body/div[1]/div[1]/div/div[3]/div[1]/h3";
const element = document.evaluate(yourstring, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM