Trim decimals from input label span using plain JavaScript

244 Views Asked by At

I'm using a wordpress plugin that's spitting out code that looks like this:

<div class=" product-addon product-addon-extra-tip">    
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="2" data-price="2" value="2"> $2 (<span class="amount">$2.00</span>)</label>
  </p>
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-1">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="5" data-price="5" value="5"> $5 (<span class="amount">$5.00</span>)</label>
  </p>
</div>

You can see that the <span> contains a dollar value with decimals. I would like to trim the decimal and trailing zeros from every instance.

I know this should be possible using toFixed(), but I cannot figure out how on earth to target just those specific <span>s. I can't simply select by the class name of amount because it is used elsewhere.

So, I need to target the <span>s with class amount inside the <div> with class product-addon. And I need to remove the decimals from the strings inside those <span>s.

2

There are 2 best solutions below

0
On BEST ANSWER

Use the following javascript to trim all decimals and trailing zeros from spans inside div with class product-addon.

var links = document.getElementsByClassName("product-addon");
var span = links[0].getElementsByTagName("span");
console.log(span.length);
for (var i = 0; i < span.length; i++) {
  span[i].innerText = span[i].innerText.split('.')[0];
}
<div class=" product-addon product-addon-extra-tip">
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="2" data-price="2" value="2">$2 (<span class="amount">$2.00</span>)</label>
  </p>
  <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-1">
    <label>
      <input type="radio" class="addon addon-radio" name="addon-2004-extra-tip-0[]" data-raw-price="5" data-price="5" value="5">$5 (<span class="amount">$5.00</span>)</label>
  </p>
</div>

0
On

So use querySelectorAll and select them

var spans = document.querySelectorAll("dov.product-addon span.amount");
console.log(spans.length);

And loop over the collection.