0

How do you run JQuery code inside of an EJS forEach loop? I am trying to read from a mongoDB document taken in through Node.js with Express as the engine. With each item, I want to create an li item with the items name as the list-item text. Currently, this is what I have:

    <% data[0].user_projects.forEach(function(project) { %>

            $('#projUL').append('<li><%= project.project_name %></li>');

    <% }); %>

When I go to the page, however, it throws no errors; but inside the source code it shows the following script, but it never renders to the page:

    <script>

            $('#projUL').append('<li>Express Project 1</li>');

    </script>

If I remove the script tags, it just inserts plain text of the same code. So, I cannot figure out how to get jQuery code inside of an EJS forEach loop. It never renders the results, no matter what I do. It only seems to take in plain text.

boom_box
  • 127
  • 1
  • 2
  • 9
  • Uh, you don't? Use ejs *templates* to emit **html**, not to generate jquery code! – Bergi Mar 29 '15 at 22:20
  • So there's no way to accomplish what I'm trying to do? EJS can only expel plain html? – boom_box Mar 29 '15 at 22:22
  • Of course you can (probably your script will work once you have instantiated a `
      `), but I mean you shouldn't. I can't see any reason not to use plain html here.
    – Bergi Mar 29 '15 at 22:24
  • I'm trying to connect these li's to li's in another div that are also created dynamically, and I need to use a counter variable to connect them, as I have no idea how many are coming in. And I have the ul instantiated later in the page, but it refuses to run the jquery. – boom_box Mar 29 '15 at 22:31
  • Regardless, imo you should try to solve this with server-side programming first before throwing jQuery at it. Btw: ["*instantiated **later** in the page*" is very much the key here](http://stackoverflow.com/q/14028959/1048572). – Bergi Mar 29 '15 at 22:35

1 Answers1

1

It is likely that the ul projUL is not in the DOM by the time that script is executed. If you still need to write some data to the HTML without using the template you could try using a jQuery ready event. First add the data server side with the script and then after you have the UL created append it.

//this will be global or use your own scope.
window.user_projects = <%= data[0].user_projects %>;
$(document).ready(function (){
   var $list = $('#projUL');
   window.user_projects.forEach(function () {
        $list.append('<li><%= project.project_name %></li>');
   });
});   
pdjota
  • 3,163
  • 2
  • 23
  • 33