Using XPath contains with querySelectorAll

Viewed 24197

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.

2 Answers

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 accomplish, 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>

Related