1

I've been staring at this code for hours now, any input appreciated.

I want to create a list in a HTML file from an array of objects using jquery append, but it justs stays blank.

HTML:

<html>
<head>
    <script src="jquery-1.10.0.js"></script>
    <script src="test.js"></script>
    <title></title>
</head>
<body>
    <div id="list">
    </div>

    <div id="template">
      <div class="info">
        <a class="url"></a>
      </div>
    </div>
</body>
</html>

Script:

function update(events) {
    var eventList = $('#list');
    eventList.empty();
    events.forEach(
        function(_event) {
            var eventsHtml = $('#template .info').clone();
            eventsHtml.find('.url').text(_event.title)
                                   .attr('href', _event.url);              
            eventList.append(eventsHtml);
        });
}
var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
update(events);
1
  • You are embedding your script before #list exists ... place script behind it, or use $(function() { ... }) to run code when the DOM is ready. Commented May 30, 2013 at 11:58

2 Answers 2

2

Assuming the JS code you show is contained in test.js, either move this line:

<script src="test.js"></script>

...to the end of the body (just before the closing </body> tag), or wrap your code in a $(document).ready() handler.

The way you currently have it, this line:

var eventList = $('#list')

...doesn't find the '#list' element because the script runs before the element is parsed. Same problem with finding '#template .info'.

You could wrap all of the code in a ready handler, or if you need to be able to call the update() function from elsewhere just wrap the initial call:

$(document).ready(function() {
    var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
    update(events);
});
Sign up to request clarification or add additional context in comments.

1 Comment

ARGH! Of course.. Thank you very much, now I can go on with my life.
0

Use the following JS code:

$(document).ready(function(){
   var events = [{title:'fu',url:'bar'}, {title:'bar',url:'fu'}];
   var eventList = $('#list');
   eventList.empty();
   events.forEach(
     function(_event) {
        var eventsHtml = $('#template .info').clone();
        eventsHtml.find('.url').text(_event.title)
                               .attr('href', _event.url);              
        eventList.append(eventsHtml);
     });
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.