Create divs from Array elements

前端 未结 4 751
孤独总比滥情好
孤独总比滥情好 2020-12-05 15:43

I have different strings in my array. Is it possible to create a divs like

for each array element in my HTML page?

相关标签:
4条回答
  • 2020-12-05 16:05

    Yeah, using a for loop:

    var arrayVariable = ['one','two','three'],
        arrayLength = arrayVariable.length;
    
    for (i = 0; i < arrayLength; i++) {
      $('<div class="results" />').text(arrayVariable[i]).appendTo('body');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Or slightly more jQuery-fied:

    var arrayVariable = ['one', 'two', 'three'];
    
    $.each(arrayVariable, function(index, value) {
      $('<div />', {
        'text': value
      }).appendTo('body');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    You could do this in vanilla JavaScript too, if you'd prefer:

    var arrayVariable = ["one", "two", "three"];
    var arrayLength = arrayVariable.length;
    var temp;
    
    for (i = 0; i < arrayLength; i++) {
      temp = document.createElement('div');
      temp.className = 'results';
      temp.innerHTML = arrayVariable[i];
      document.getElementsByTagName('body')[0].appendChild(temp);
    }

    It's worth considering where the id is coming from; if more than one element is to be produced by this for loop, it might be better (depending on where, and how, the id is assigned) to use a class instead, as I did in both of my suggestions, as the id must be unique within the document.

    While this answer was written quite a while ago, I felt it worth updating to reflect the possibilities offered by the (relatively new) Array.prototype.forEach(), which iterates over each element of a given array, and applies a function for each iteration. For example, given the HTML:

    <ul id="fruits"></ul>
    

    And the JavaScript:

    var fruitsList = document.getElementById('fruits'),
        li = document.createElement('li'),
        clone;
    ['apples','bananas','cranberries'].forEach(function (fruit, index) {
        clone = li.cloneNode();
        clone.textContent = index + ': ' + fruit;
        fruitsList.appendChild(clone);
    });
    

    Resulting in the output:

    <ul id="fruits">
        <li>0: apples</li>
        <li>1: bananas</li>
        <li>2: cranberries</li>
    </ul>
    

    var fruitsList = document.getElementById('fruits'),
      li = document.createElement('li'),
      clone;
    ['apples', 'bananas', 'cranberries'].forEach(function(fruit, index) {
      clone = li.cloneNode();
      clone.textContent = index + ': ' + fruit;
      fruitsList.appendChild(clone);
    });
    <ul id="fruits"></ul>

    References:

    • JavaScript:
      • Array.prototype.forEach().
      • document.createElement().
      • document.getElementById().
      • document.getElementsByTagName().
      • Element.className.
      • Element.innerHTML.
      • Node.appendChild().
      • Node.cloneNode().
      • Node.textContent.
    • jQuery:
      • appendTo().
      • $.each().
      • text().
    0 讨论(0)
  • 2020-12-05 16:05

    You can use

    var results = ['result 1', 'result 2', 'result 3'];
    
    $.each(results, function(idx, value){
      var newdiv = $('<div>',{class: 'results', text: value});
      $('body').append( newdiv  );
    });
    

    used $.each() docs, and also changed the id to class since id needs to be unique.

    demo at http://jsfiddle.net/gaby/FuPF7/

    0 讨论(0)
  • 2020-12-05 16:08

    A Basic For Loop + jQuery should do it. Just replace body with a selector for the container you want to add the divs to. Here is a fiddle showing the technique in use.

    var myCars=new Array("Saab","Volvo","BMW");
    
    for(var x=0; x<myCars.length; x++){
        $('body').append('<div id="' + myCars[x] + '">' + myCars[x] + '</div>');
    }
    
    0 讨论(0)
  • 2020-12-05 16:23

    Sure, simple example without using any frameworks or libraries:

    var cars = 'Saab,Volvo,BMW,GMC,Nissan,Ford'.split(',');
    for (var c in cars) {
        var newElement = document.createElement('div');
        newElement.id = cars[c]; newElement.className = "car";
        newElement.innerHTML = cars[c];
        document.body.appendChild(newElement);
    } 
    

    You can take a look at how this works using jsFiddle here: http://jsfiddle.net/Shaz/geNNa/

    0 讨论(0)
提交回复
热议问题