Auryn
Auryn

Reputation: 1176

XPath select on child nodes

I am currently trying to make a new xpath on a child node. But it doesn't work.

How can I archive this?

The idea is:

    xpath.select('//*[contains(@class, "product-grid__item")]', doc).forEach(node => {
     node = node as Node;

     xpath.select('/a /*[contains(@class, "desc-height")] /strong', node).forEach(z => {
       z = z as Node;
       console.log(z.textContent);
     })
   })

But the second request does not select on the nodes, it selects on the document.

Upvotes: 0

Views: 382

Answers (1)

Alejandro
Alejandro

Reputation: 1882

The expression

/a/*[contains(@class, "desc-height")]/strong

is an absolute location path and it will evaluate equally from every context node.

You need a relative location path like

a/*[contains(@class, "desc-height")]/strong

Note: some literature will always show you relative XPath expression starting with . abbreviate syntax like ./a/*[contains(@class, "desc-height")]/strong. That it's not needed. Some XPath engines not aligned with the specs might only parse this kind of expression just because.

Upvotes: 2

Related Questions