简体   繁体   中英

CSS / XPATH Selector Query

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 !

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 thelast 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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM