简体   繁体   English

CSS / XPATH 选择器查询

[英]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,对我们的 CSS 和 Xpath 选择器世界的一个小问题我已经成功地使用 XPATH 获得了一个文本值,但我无法使用 CSS 选择器成功,

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,我可以获得值“270,38K”而没有 XPATH 问题,

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

Res -> 270,38K ( good )分辨率 -> 270,38K(

But i can't achieve it with a CSS Selector,但我无法使用 CSS 选择器实现它,

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

Res -> euros (€) !资源 -> 欧元 (€) ! 270,38K ( wrong ) 270,38K(错误

Do you have a clue to only get text value of span (without children content) with a css selector?您是否有线索只能使用 css 选择器获取 span 的文本值(没有子内容)?

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您的选择器很好,您只需要通过获取包含所需文本的文本节点来做一些额外的工作,因为 css 选择器无法获得这些文本

Get thelast child node (which should be a text node) of the element by using lastNode and get the textContent of that使用 lastNode 获取元素的最后一个子节点(应该是文本节点)并获取该元素的 textContent

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

or use the childNodes list或使用childNodes列表

let nodes = document.querySelector('span.piggy').childNodes;
console.log( nodes[nodes.length-1].textContent );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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