Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Target second span text when a common class is being used

I have some html snippet

<p>
<span class="et-product-ammount">1</span><span>&nbsp;x&nbsp;</span><bdi><span class="et-cart-product-price">CA$</span><span id="sec_price_4082395074_1161" class="et-cart-product-price">89</span></bdi>
</p>

The first instance of .et-cart-product-price shows the currency symbol and the second shows the price.

To get the currency symbol i am using jquery like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var currency_currency_symbol = $("span.et-cart-product-price").text();

How can i select the text in the first and second occurrence of the et-cart-product-price class respectively?.

>Solution :

Your selector finds multiple elements.

By calling text() on the array, the values are merged.

Since you want both values in a seperate variable, you’ll need to alter the selector, and use (eg) map() to convert the DOM element to the value you need. I’ve use a list syntax to assign the array values to 2 variables:

var currency_currency_spans = Array.from($("span.et-cart-product-price"));

var [ symbol, price ] = currency_currency_spans.map(e => e.innerHTML);
console.log('Symbol:', symbol);
console.log('Price:', price);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <span class="et-product-ammount">1</span>
  <span>&nbsp;x&nbsp;</span>
  <bdi>
    <span class="et-cart-product-price">CA$</span>
    <span id="sec_price_4082395074_1161" class="et-cart-product-price">89</span>      </bdi>
</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading