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.

Share Improve this question edited Nov 4, 2018 at 12:19 VLAZ 29.1k9 gold badges62 silver badges84 bronze badges asked Nov 4, 2018 at 12:07 NeilNeil 1151 gold badge1 silver badge8 bronze badges 3
  • 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
Add a ment  | 

2 Answers 2

Reset to default 2

After 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