Change divs with the same class

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 this but it changes all numbers to the first value

    
asked by anonymous 19.10.2016 / 16:05

5 answers

6

You have to do the concat for each one, the suggestion here is to do with 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><tdclass="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>
    
19.10.2016 / 16:15
4

Some ways to do it:

1 - Using JQuery ( running example )

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

2 - Using only CSS ( example running )

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

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

3 - Using only Javascript ( example running )

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.

    
19.10.2016 / 20:31
1

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

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

I did not test but I believe it will be something in these lines.

    
19.10.2016 / 16:29
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>
    
19.10.2016 / 16:25
0

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

$('.valor').each(function(){
    this.innerHTML+='%';
});
    
19.10.2016 / 17:19