简体   繁体   English

如何使用document.querySelector使用document.querySelector从节点中选择文本的特定输出?

[英]How do I use document.querySelector to select a particular output of text from a node using document.querySelector?

How do I use document.querySelectorAll() to select a particular output of text from the code below? 如何使用document.querySelectorAll()从下面的代码中选择特定的文本输出?

I'd like to capture the result in a variable and am attempting to do so with the following code: 我想将结果捕获到变量中,并尝试使用以下代码进行捕获:

let result = document.querySelectorAll('.coinmarketcap-currency-widget');

The querySelectorAll() returns a node list. querySelectorAll()返回节点列表。 My question is how do I get to the particular child node that I need? 我的问题是如何到达所需的特定子节点?

I need to select the text from a span tag element with the value of "0.044763 USD". 我需要从跨度标签元素中选择值为“ 0.044763 USD”的文本。 My question is how do I get to the particular child node that I need (0.044763 USD)? 我的问题是如何到达所需的特定子节点(0.044763 USD)?

<div class="coinmarketcap-currency-widget">
<div style="border:2px">
<div><div style="float:right;width:67%;">

<span style="font-size: 18px;"><a href="http://coinmarketcap.com/" target="_blank">TRON (TRX)</a></span> <br>            
<span style="font-size: 16px;">

    0.044763 USD 

    <span style="color:#d14836">(-3.85%)</span></span>            

Use this selecor .coinmarketcap-currency-widget div > span:last-child to get the target span and split the innerHTML to get the value 使用此selecor .coinmarketcap-currency-widget div > span:last-child来获取目标范围,并拆分innerHTML来获取值

 let result = document.querySelectorAll('.coinmarketcap-currency-widget div > span:last-child'); console.log(result[0].innerHTML.split("<span")[0]); 
 <div class="coinmarketcap-currency-widget"> <div style="border:2px"> <div> <div style="float:right;width:67%;"> <span style="font-size: 18px;"> <a href="http://coinmarketcap.com/" target="_blank">TRON (TRX)</a> </span> <br> <span style="font-size: 16px;"> 0.044763 USD <span style="color:#d14836">(-3.85%)</span> </span> </div> </div> </div> </div> 

我最终将以下内容用作简单的解决方案,并将其保存到变量中。

document.getElementsByTagName('span')[1].innerText;

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

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