How to get the value of several items and change according to my if

2

I have a list of items (which comes from the database), I need to compare each item from one of those and if the value is 0 change the text. Below is the function I am trying to use to change the value of the item.

function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        validaPreco = 'Grátis'
      }
    }
  }

When I use the document.getElementsByClassName('comprar')[0].innerHTML line in the browser console I have returned the value I want to use to compare, however I want to compare all items that are brought from the database.

And this is the line of code where the price appears

<a href="detalhe/{{item.id}}" onclick="subir()"><button class="comprar">$ {{item.originalValue}}</button></a>

Just to make it clear, I'm using polymer 2, the firebase-query element to bring the data in.

    
asked by anonymous 12.06.2018 / 14:25

1 answer

1

In your code:

function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        validaPreco = 'Grátis'
      }
    }
  }

You set the value of validaPreco to "Free", but this will not be reflected in the DOM because validaPreco and preco[n].innerHTML are different objects, even if one is copying the other. What you need to do is modify the object in the DOM:

function isFree(){
    var preco = document.getElementsByClassName('comprar');
    for(n = 0; n < preco.length; n++){
      var validaPreco = preco[n].innerHTML;
      if(validaPreco == '$ 0'){
        preco[n].innerHTML = 'Grátis'
      }
    }
  }

See an example:

function isFree() {
  var preco = document.getElementsByClassName('comprar');
  for (n = 0; n < preco.length; n++) {
    var validaPreco = preco[n].innerHTML;
    if (validaPreco == '$ 0') {
      preco[n].innerHTML = 'Grátis'
    }
  }
}

isFree();
<ul>
  <li class="comprar">$ 10,00</li>
  <li class="comprar">$ 0</li>
  <li class="comprar">$ 99,99</li>
  <li class="comprar">$ 0</li>
</ul>
    
12.06.2018 / 14:31