admin管理员组文章数量:1287577
I'm quite familiar with XPath in PHP, and wanted to use it within JavaScript with the end goal of making an extension to help me with something.
I have the following XPath which works and tested in the dev tools on Chrome:
//div[contains(@data-bt,'rank')]
However, it doesn't seem to work with querySelectorAll. Yet the following does:
document.querySelectorAll("div[data-bt]")
I've also noticed that using //
on the XPath seems to throw an error saying its not a valid selector.
I'm quite familiar with XPath in PHP, and wanted to use it within JavaScript with the end goal of making an extension to help me with something.
I have the following XPath which works and tested in the dev tools on Chrome:
//div[contains(@data-bt,'rank')]
However, it doesn't seem to work with querySelectorAll. Yet the following does:
document.querySelectorAll("div[data-bt]")
I've also noticed that using //
on the XPath seems to throw an error saying its not a valid selector.
-
3
The latter is a CSS selector not XPATH.
.querySelectorAll
requires CSS selectors. – VLAZ Commented Nov 4, 2018 at 12:15 - thank you, seems i was getting confused between xpaths and querySelectors. Also that you for working my question better :) – Neil Commented Nov 4, 2018 at 12:35
- Beware of the XY trap – Jonathan Commented Nov 4, 2018 at 12:38
2 Answers
Reset to default 2After reading about querySelector
. I found the following does the same as the XPath I was trying to achieve.
x = document.querySelectorAll('div[data-bt*="rank"]');
for (var i = 0; i < x.length; i++) {
json_str = x[i].getAttribute('data-bt');
data = JSON.parse(json_str);
console.log(data.id);
}
Even though I'm not exactly sure what it is that you are trying to acplish, here is a snippet that might help.
const nodeList = document.querySelectorAll('[data-bt*="rank"]');
const identifiers = Array.from(nodeList).map(node =>
({
id: node.dataset.id,
bt: node.dataset.bt
}));
console.log(identifiers);
<div data-id="1" data-bt="rank1">Rank 1</div>
<div data-id="2" data-bt="rank2">Rank 2</div>
<div data-id="3" data-bt="rank3">Rank 3</div>
本文标签: javascriptUsing XPath contains with querySelectorAllStack Overflow
版权声明:本文标题:javascript - Using XPath contains with querySelectorAll - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741297557a2370903.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论