1

I am writing a script inside a tag.

<ul class="boxes_tree">
  <li><strong>data</strong></li>
  <script type="text/javascript">
    var itemStr ='[data1,data2]';
    itemStr=$.parseJSON(itemStr);
    if(itemStr){
          for (var key in itemStr)
          {
             if (itemStr.hasOwnProperty(key))
             {
                itemStr[key];
             }
          }
    }
  </script>
</ul>

now inplace of itemStr[key]; I want to add a li tag with itemStr[key] as content of li tag.

How can I achieve this?

Glauco Vinicius
  • 2,447
  • 1
  • 21
  • 37
Seeker
  • 2,066
  • 5
  • 38
  • 74

3 Answers3

0

You can use document.write:

document.write("<li>" + itemStr[key] + "</li>");

As far as I know, that is the only way to achieve what you are trying to do. However, you might want to reconsider your design altogether. because using document.write is considered a poor practice.

Community
  • 1
  • 1
jevakallio
  • 33,015
  • 3
  • 95
  • 111
0

Works for me with valid JSON

You use jQuery anyway so DEMO

$(function() {
  var itemStr ='[{"var":"data1"},{"var":"data2"}]';
  itemStr=$.parseJSON(itemStr);
  var $ul = $("#tree");
  if(itemStr){
    $(itemStr).each(function(i, val) {
      $ul.append("<li>"+val.var+"</li>");
    });
  }
});

document.write version: DEMO

mplungjan
  • 134,906
  • 25
  • 152
  • 209
0

How about move it to the head and make it this way with jQuery?

$('.boxes_tree').append("<li>" + itemStr[key] + "</li>");
gregjer
  • 2,715
  • 2
  • 17
  • 18