0

I have a Javascript array of unknown length and I'd love to make some of its fields show up in my html page. I've tried to make a function in my js library to print them calling it directly through my html code

<body onload="parser()">
   <div id="list">
       <script> load_list() </script>
   </div>
</body>

the function parser() extract the infos from an xml file and put them in the array. The function load_list is the following

function load_list () {
     document.write ("<ul>");
     for (i=0; i< array.length; i++) {
         document.write ("<li><a href='javascript:change("+array[i].x+")'>");
         document.write (array[i].name);
         document.write ("</a></li>");
     }
}
Janinho67
  • 145
  • 3
  • 16

2 Answers2

3

Try

<div id="list">
</div>

<script>
    var subjects = [{
        x: '1',
        name: 'One'
    }]

    function load_list(){
        var ul = document.createElement('ul');
        document.getElementById('list').appendChild(ul);
        for (i=0; i< subjects.length; i++) {
            var li = document.createElement('li');
            var a = document.createElement('a');
            a.innerHTML = subjects[i].name;
            a.setAttribute('href', "javascript:change("+subjects[i].x+")")
            li.appendChild(a);
            ul.appendChild(li);
        }
    }


    function parser(){

        //do parsing logic


        load_list()
    }

</script>

Demo: Fiddle

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
2

document.write is essentially deprecated (not officially).

Further reading: Why is document.write considered a "bad practice"?

Also, the creating of elements through straight text is again unwise, as it doesn't properly add them to the DOM.

Try this:

subjects = ["test","test2"];
array = [{x:"test",name:"name"},{x:"test2",name:"name2"}];

for (i=0; i< subjects.length; i++) {
    var li = document.createElement("li");
    var a = document.createElement("a");
    a.setAttribute("href","javascript:change("+array[i].x+")");
    a.innerHTML = array[i].name;
    li.appendChild(a);
    document.getElementById('listUL').appendChild(li);
}

<div id="list">
    <ul id="listUL">

    </ul>
</div>

See it working here:

http://jsfiddle.net/wdkmz/

Community
  • 1
  • 1
MasNotsram
  • 2,047
  • 14
  • 27