Assign multiple elements to different values using the same function

2

I have 5 IDS (5 DOM elements) and I need to use JQuery's text () function to add different text to each one of them.

$("#ID1").text("bla");

$("#ID2").text("blabla");

....

There is a simpler way of doing this, if the texts were the same, you could comma-separated the selectors, but they are not.

I thought of something like:

.text(function() {
$("#ID1") = "bla";
$("#ID2") = "blabla";
});

Anyway, any suggestion, even for good practice and to keep the code simplified and clean.

    
asked by anonymous 14.01.2015 / 14:13

2 answers

2

You can create a dictionary format object, where the keys are the IDs of the divs, and the values are their text. Then just go through the dictionary to populate the divs:

var textos = {
    "id1" : "bla",
    "id2" : "blabla",
    "foo" : "bar" // , etc
};
$.each(textos, function(chave, valor) {
   $('#' + chave).text(valor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="id1"></div>
<div id="id2"></div>
<div id="foo"></div>
    
15.01.2015 / 01:17
2

  var addText = function(array, element){
         
        $(element).each(function(i){
            $(this).text(array[i]);
        }); 
    };
    
    $(function(){
      var array = [
          "meu primeiro texto",
          "Meu segundo Texto",
          "Meu terceiro texto",
          "E assim por diante",
       ];
     
        addText(array, '.CLASS');
    });


    addText(array, '[id^=ID]');
.CLASS{
  border:1px solid red;
  height:50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script><divclass="CLASS"></div>
    <div class="CLASS"></div>
    <div class="CLASS"></div>
    <div class="CLASS"></div>
    <div class="CLASS"></div>
    
14.01.2015 / 15:02