[英]How to access a specific text inside a span in javascript
<div id = "item_container">
<div class="price">
<span class ="discounted">
"
$150
"
</span>
"$125 for 2 months"
<br>
"
Handling Fee: $3.15
"
</div>
</div>
Can someone help me or point me to the right direction on how to access the text "$125 for 2 months" using javascript?有人可以帮助我或为我指出如何使用 javascript 访问文本“$125 for 2 Month”的正确方向吗?
I tried using querySelector but it will only get the $150 text.我尝试使用 querySelector 但它只会得到 150 美元的文本。
var discounted_price = document.querySelector('#item_container > div.price > span').innerHTML;
console.log(discounted_price);
The code I used will not get the remaining text which i need.我使用的代码不会得到我需要的剩余文本。
If the HTML is always like that, you can query .discounted
then transverse to the next sibling .如果 HTML 总是那样,你可以查询.discounted
然后横向到下一个兄弟。
Once you get there, you can get thenodeValue for that text node到达那里后,您可以获得该文本节点的nodeValue
const discounted_price = document.querySelector('.discounted') console.log(discounted_price.nextSibling.nodeValue);
<div id="item_container"> <div class="price"> <span class="discounted"> " $150 " </span> "$125 for 2 months" <br> " Handling Fee: $3.15 " </div> </div>
The text you're looking for is not inside the span
, instead it's the next sibling node of the span您要查找的文本不在span
,而是在span
的下一个兄弟节点
const text = document.querySelector(".discounted").nextSibling.textContent.trim(); console.log(text)
<html> <div id = "item_container"> <div class="price"> <span class ="discounted"> " $150 " </span> "$125 for 2 months" <br> " Handling Fee: $3.15 " </div> </div> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.