jQuery does not display the cents in a price list

1

I'm in need of help with the following question:

In an HTML price list, I want to create a function using jQuery / JavaScript so that as soon as the page loads, we select the HTML object, turn it into a string, split it after the comma, and then replace the object HTML by variable

$(document).ready(function() {
  var stringin = $('.priceList', 'ul', 'li').toString();
  var formatedPrice = $(stringin).split(',');

  $('.priceList', 'ul', 'li').innerHTML(formatedPrice[0]);
});
.price {
  position: absolute;
  top: 100px;
  left: 100px;
}
<!doctype html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Cents</title>
  <link rel="stylesheet" href="main.css">

  <script src="jquery-3.2.1.min.js"></script>
</head>

<body>

  <div class="priceList">
    <ul>
      <li>R$ 50,89</li>
      <li>R$ 188,43</li>
      <li>R$ 1200,24</li>
    </ul>
  </div>

</body>

</html>

Above was my idea, the steps were: create two variables, the first to select the object and transform into a string, the second I split the string in two from the comma. So we get the first array "[0]" and change the HTML. While I am writing the doubt I have stopped to think that in case, as I am dealing with more than one value, would it be correct to make a vector, or am I mistaken?

While this is going to try to make a vector, anything I put here works.

Anyway, I need help, if there is another way to accomplish the goal please tell me. maybe another logic, or else with pure JavaScript ...

    
asked by anonymous 02.10.2018 / 14:45

1 answer

4

One problem also is that this selector is invalid: $('.priceList', 'ul', 'li') . The correct would be: $('.priceList ul li') ( li child of a ul child of class .priceList ).

Actually using .split is simpler, but you have to loop through each element:

$(document).ready(function() {
   $('.priceList ul li').each(function(){
      var stringin = $(this).text();
      var formatedPrice = stringin.split(',')[0];
      $(this).text(formatedPrice);
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="priceList">
    <ul>
      <li>R$ 50,89</li>
      <li>R$ 188,43</li>
      <li>R$ 1200,24</li>
    </ul>
  </div>

Using pure JavaScript would look like this:

document.addEventListener("DOMContentLoaded", function(){
   var vals = document.querySelectorAll('.priceList ul li');
   for(var x=0; x<vals.length; x++){
      var stringin = vals[x].textContent;
      var formatedPrice = stringin.split(',')[0];
      vals[x].textContent = formatedPrice;
   }
});
<div class="priceList">
    <ul>
      <li>R$ 50,89</li>
      <li>R$ 188,43</li>
      <li>R$ 1200,24</li>
    </ul>
  </div>
    
02.10.2018 / 15:33