简体   繁体   中英

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?

I tried using querySelector but it will only get the $150 text.

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 .

Once you get there, you can get thenodeValue for that text node

 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

 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>

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