2

A little question to our world of CSS & Xpath Selector I've successfully obtained a text value with XPATH but I can't succeed with a CSS Selector,

Here is my example:

<span class="piggy">
    <i class="fa fa-try"></i>
    <strong>euros (€) !</strong>
270,38K</span>

I can get value "270,38K" without problem with XPATH,

document.evaluate('//*[@id="wrap"]/span/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.textContent.trim();

Res -> 270,38K (good)

But i can't achieve it with a CSS Selector,

document.querySelector('span.piggy').innerText.trim();

Res -> euros (€) ! 270,38K (wrong)

Do you have a clue to only get text value of span (without children content) with a css selector?

Thank you all !

1
  • Good one I too would have wondered the same. Btw did you try this in firefox as well? Commented Jan 27, 2020 at 2:12

1 Answer 1

2

Your selector is fine you just have to do a little extra work by getting the text node that contains the wanted text as those cant be obtained by css selector

Get the last child node (which should be a text node) of the element by using lastNode and get the textContent of that

document.querySelector('span.piggy').lastNode.textContent

or use the childNodes list

let nodes = document.querySelector('span.piggy').childNodes;
console.log( nodes[nodes.length-1].textContent );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.