How to get the span number by an ID

Asked

Viewed 173 times

2

I have the following situation:

<span class="integral" id="precoVinho01">
   <span data-attr="Integer">100</span>
   <span data-attr="Decimal">,99</span>
</span>

How do I manage to collect only the 100,99?

I tried in the following ways:

$('#precoVinho01').find("span").each(function(index) {
    var text = $(this).text();
    $(this).replaceWith(text);
 });
// Não funcionou, pois apagou o span inteiro, logo, perdeu a referencia data-attr para aparecer o número.

And I tried this way too.

var price01 = $('#precoVinho01').html().replace(/[^\d]+/g,'').replace(',', '.');

// Não funcionou, pois o numero virou 10099, e quando tentei colocar toFixed para ter o decimal

var price01 = $('#precoVinho01').html().replace(/[^\d]+/g,'').toFixed(2).replace(',', '.');

//não funcionou

I appreciate the help =)

1 answer

3


In vanilla javascript you can use the property innerText of the element <span>.

let span = document.getElementById("precoVinho01");
console.log(span.innerText.replace(/\s/g, ''))
<span class="integral" id="precoVinho01">
   <span data-attr="Integer">100</span>
   <span data-attr="Decimal">,99</span>
</span>

With Jquery use the method text()

console.log($("#precoVinho01").text().replace(/\s/g, ''))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="integral" id="precoVinho01">
   <span data-attr="Integer">100</span>
   <span data-attr="Decimal">,99</span>
</span>

  • It worked a lot... thanks! I used the Jquery method. Have any explanation of why . text worked and . html did not?

  • 1

    Because the text() function is an abstraction about the property innerText and according to the manual innerText returns the text content of the "as rendered" element and html() returns the HTML of the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.