How to change multiple div with same class with different values?

Asked

Viewed 121 times

0

I have several Ivs with same class and different values. I wanted to select all of them, take each one’s value and add HTML to each with new values. With the code I made, I can take the value, turn it into an integer, divide it by 600 and add the html I want. But I can only do it for the first div. Someone can help?

$(document).ready(function() {
$wrapper = document.querySelector('.preco-promocional'),

precoTOTAL = $wrapper.innerHTML;

var s3 = precoTOTAL.replace(/[\D]+/g,'');
var valor = parseInt(s3); 
var garrafa = valor / 600;
    HTMLNovo = '<div style=" color:#4b1472; font-size:11px;">Preço para 6 unidades<br>Cada garrafa por R$ '+garrafa+',00</div>';

$wrapper.insertAdjacentHTML('beforeend', HTMLNovo);

  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div class="preco-promocional">R$ 1.500,00</div>
        
      <div class="preco-promocional">R$ 2.500,00</div>
        
      <div class="preco-promocional">R$ 3.500,00</div>
        

  • cfgallo, welcome to Stack Overflow in English. Start here for an overview of the site. https://answall.com/tour

1 answer

0


HTML5 defines a getElementsByClassName method that allows us to select sets of document elements based on the identifiers that are in their class attribute.

var items = document.getElementsByClassName("preco-promocional")

The method getElementsByClassName () returns a collection of child elements of an element with the specified class name, such as a Nodelist object.

The Nodelist object represents a collection of nodes. Nodes can be accessed by index numbers. The index starts at 0.

You can use the property length of the Nodelist object to determine the number of child nodes with the specified class name

$(document).ready(function() {

var items = document.getElementsByClassName("preco-promocional"),i, len;

// percorre todos os elementos com o nome de classe ".preco-promocional"
for (i = 0, len = items.length; i < len; i++) {
  precoTOTAL = items[i].innerHTML;

  var s3 = precoTOTAL.replace(/[\D]+/g,'');

  var valor = parseInt(s3); 
  var garrafa = valor / 600;

  HTMLNovo ='<div style=" color:#4b1472; font-size:11px;">Preço para 6 unidades<br>Cada garrafa por R$ '+garrafa.toFixed(2)+'</div>';

  items[i].insertAdjacentHTML('beforeend', HTMLNovo);

}
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div class="preco-promocional">R$ 1.500,00</div>
        
      <div class="preco-promocional">R$ 2.500,00</div>
        
      <div class="preco-promocional">R$ 3.500,00</div>
        

  • Perfect! Thank you very much!

Browser other questions tagged

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