Change Divs with the same class

Asked

Viewed 711 times

2

<table>
    <tr>
        <td class="valor"> 33</td>
        <td class="valor"> 88</td>
        <td class="valor"> 55</td>
        <td class="valor"> 36</td>
        <td class="valor"> 79</td>
        <td class="valor"> 35</td>
    </tr>
</table>

I need to put the percentage symbol after the number

<script type="text/javascript">
    $(document).ready(function(){
       var valor = $('.valor').html();
       $('.valor').text(valor+'%');
    });                   
</script>

I tried to do it this way but it changes all the numbers to the first value

  • You have already received 5 answers. Please consider choosing one of them for sure to help other people who also have the same question. Hugs.

5 answers

6

You have to do the Concat for each one, the suggestion here is to do with the each:

  $(document).ready(function(){
       var valor = $('.valor').each(function(){
       		val = $(this).html()
          $(this).html(val + '%')
       })   
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="valor"> 33</td>
<td class="valor"> 88</td>
<td class="valor"> 55</td>
<td class="valor"> 36</td>
<td class="valor"> 79</td>
<td class="valor"> 35</td>
</tr>
</table>

4

Some ways to do:

1 - Using Jquery (working example)

$('.valor').append('%');

2 - Using CSS only (working example)

.valor:after {
  content: "%";
}

This technique uses the pseudo-element ::after of CSS2. Check out the compatibility with different browsers.

3 - Using Javascript only (working example)

var valores = document.getElementsByClassName('valor');

for (var i=0; valores[i]; i++) {
  valores[i].innerHTML += '%';
}

This option does not need Jquery, and is also compatible with some older browsers.

1

You have to do this process for each element (obj) that has assigned the referred class. You can access object data with wrapper Jquery $(this).

<script type="text/javascript">
    $(document).ready(function(){
       $('.valor').each(function(obj) {
          var valor = $(this).html();
          $(this).text(valor+'%');
       }); 
    });
</script>

I have not tested but I believe it will be something in these lines.

0

<script type="text/javascript">
$(document).ready(function(){
   var valores = $('.valor');
    for (i = 0; i < valores.length; i++) { 
        var valor = valores[i];
        valor.textContent = valor.textContent + '%';
    }
});
</script>

0

You must iterate over all items. You can do this using the function each. You can also access the element directly, as in the code below, instead of using the html function().

$('.valor').each(function(){
    this.innerHTML+='%';
});

Browser other questions tagged

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