最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Append for loop to div in html - Stack Overflow

programmeradmin3浏览0评论

So I'm trying to learn javascript and I think I have a working json script with a loop to grab the data but I'm having trouble figuring out how to append the data to my div. After I figure this out I'm going to redo it in jquery (because I'm trying to learn that as well).

Let's say my div id is #wrapper

for (var i = 0; i < providerlisting.length; i++) {
document.write('<div class="entry panel row"> \
    <div class="large-4 columns first"> \
            <div class="name">' + providerlisting[i].nametitle + '</div> \
            <div class="specialty">' + providerlisting[i].caretype + '</div> \
            <div class="peferred">' + providerlisting[i].preferredprovider + '</div> \
        </div> \
        <div class="large-3 columns second"> \
            <div class="address">' + providerlisting[i].address1 + '<br /> \
            ' + providerlisting[i].address2 + '<br /> \
            ' + providerlisting[i].citystatezip + ' \
            </div> \
        </div> \
        <div class="large-3 columns third"> \
            <img src="' + providerlisting[i].coverage + '" alt="example"> \
        </div> \
        <div class="large-2 columns fourth"> \
            <div class="status">' + providerlisting.status + '</div> \
            <a data-dropdown="actionsMenu2" class="actions button small secondary round dropdown" href="#">Actions</a><br> \
            <ul id="actionsMenu2" data-dropdown-content="" class="f-dropdown"> \
                <li><a href="' + providerlisting[i].psn + '">Generate PSN</a></li> \
                <li><a href="' + providerlisting[i].dcontact + '">Download Contact</a></li> \
                <li><a href="' + providerlisting[i].save + '">Save to Provider List</a></li> \
                <li><a href="' + providerlisting[i].rating + '">View Healthgrades Rating</a></li> \
            </ul> \
        </div> \
    </div>  \
')};

So I'm trying to learn javascript and I think I have a working json script with a loop to grab the data but I'm having trouble figuring out how to append the data to my div. After I figure this out I'm going to redo it in jquery (because I'm trying to learn that as well).

Let's say my div id is #wrapper

for (var i = 0; i < providerlisting.length; i++) {
document.write('<div class="entry panel row"> \
    <div class="large-4 columns first"> \
            <div class="name">' + providerlisting[i].nametitle + '</div> \
            <div class="specialty">' + providerlisting[i].caretype + '</div> \
            <div class="peferred">' + providerlisting[i].preferredprovider + '</div> \
        </div> \
        <div class="large-3 columns second"> \
            <div class="address">' + providerlisting[i].address1 + '<br /> \
            ' + providerlisting[i].address2 + '<br /> \
            ' + providerlisting[i].citystatezip + ' \
            </div> \
        </div> \
        <div class="large-3 columns third"> \
            <img src="' + providerlisting[i].coverage + '" alt="example"> \
        </div> \
        <div class="large-2 columns fourth"> \
            <div class="status">' + providerlisting.status + '</div> \
            <a data-dropdown="actionsMenu2" class="actions button small secondary round dropdown" href="#">Actions</a><br> \
            <ul id="actionsMenu2" data-dropdown-content="" class="f-dropdown"> \
                <li><a href="' + providerlisting[i].psn + '">Generate PSN</a></li> \
                <li><a href="' + providerlisting[i].dcontact + '">Download Contact</a></li> \
                <li><a href="' + providerlisting[i].save + '">Save to Provider List</a></li> \
                <li><a href="' + providerlisting[i].rating + '">View Healthgrades Rating</a></li> \
            </ul> \
        </div> \
    </div>  \
')};
Share Improve this question edited Aug 28, 2013 at 13:54 Itay 16.8k2 gold badges56 silver badges72 bronze badges asked Aug 28, 2013 at 13:51 ChadChad 4905 silver badges14 bronze badges 3
  • See this answer: stackoverflow./a/5677816/467133 Good luck with learning jQuery! – David Hewitt Commented Aug 28, 2013 at 13:55
  • My advice would be to delete everything and start over, as that is a mess! Avoid using document.write and long strings of HTML. – adeneo Commented Aug 28, 2013 at 13:56
  • 1 Adeneo, I'm trying to learn javascript. Please try to be constructive in the future. – Chad Commented Aug 28, 2013 at 13:58
Add a ment  | 

2 Answers 2

Reset to default 4

Don't use document.write, that's a direct output (where ever the <script> may lie). And, without getting in to DOM objects, you're going to need to append to .innerHTML. e.g.

var wrapper = document.getElementById('wrapper');

for (...){
  /*document.write(*/
  wrapper.innerHTML +=
    '<div ...'
  ;
  /*);*/
}

Now, you could start using DOM elements instead. for example:

var wrapper = document.getElementById('wrapper');

for (...){
  // create the outer div (with classes 'entry panel row'):
  var entry_panel_row = document.createElement('div');

  // add the class names:
  entry_panel_row.className = 'entry panel row';

  // instead of document.write, add the HTML to this new element...
  entry_panel_row.innerHTML += '<div class="large-4 ...</div>';

  // now append the element (as a whole) to wrapper
  wrapper.appendChild(entry_panel_row);
}

Going further, instead of using strings, you can create the elements one by one appending them to each parent. Then, once you've piled the entire DOM element in to entry_panel_row you can proceed to wrapper.appendChild(entry_panel_row).


jQuery is (a little) easier than el = document.createElement and parent.appendChild(el) over and over, and the nomenclature takes a bit getting used to, but here's what you had. I figure I would translate it so you can see jQuery (you had mentioned learning it):

for (var i = 0; i < providerlisting.length; i++){
  var pl = providerlisting[i]; // shorthand reference

  // begin building you DOM element
  $('<div>')
    .addClass('entry panel row') // css classes
    .append( // children
      $('<div>').addClass('large-4 columns first').append(
        $('<div>').addClass('name').text(pl.nametitle),
        $('<div>').addClass('specialty').text(pl.caretype),
        $('<div>').addClass('preferred').text(pl.preferredprovider)
      ),
      $('<div>').addClass('large-3 columns second').append(
        $('<div>').addClass('address').html(pl.address1 + '<br />' + pl.address2 + '<br />' + pl.citystatezip)
      ),
      $('<div>').addClass('large-3 columns third').append(
        $('<img>').attr({'src':pl.coverage,'alt':'example'})
      ),
      $('<div>').addClass('large-2 columns fourth').append(
        $('<div>').addClass('status').text(pl.status),
        $('<a>').addClass('actions button small secondary round dropdown').prop('href','#').data('dropdown','actionsMenu2').text('Actions'),
        '<br />',
        $('<ul>').prop('id','actionsMenu2').addClass('f-dropdown').data('dropdownContent','').append(
          $('<li>').append(
            $('<a>').prop('href',pl.psn).text('Generate PSN')
          ),
          $('<li>').append(
            $('<a>').prop('href',pl.dcontact).text('Download Contact')
          ),
          $('<li>').append(
            $('<a>').prop('href',pl.save).text('Save to Provider List')
          ),
          $('<li>').append(
            $('<a>').prop('href',pl.rating).text('View Healthgrades Rating')
          ),
        )
      )
    )
    .appendTo('#wrapper'); // add it to #wrapper
}

You can use

document.getElementById('wrapper').innerHtml = document.getElementById('wrapper').innerHtml + 'new content';
发布评论

评论列表(0)

  1. 暂无评论