I'm not even sure if this is how you're supposed to do it, but this is what I have so far:

$.getJSON("/api/get_categories", function(data){
    var items = [];
   $.each(data["categories"], function(key, value){

    items.push('<div class="card"><div class="card waves-effect waves-block waves-light"</div><div class="card-content"><span class="card-title activator grey-text text-darken-4">'+value+'</span></div></div>');



The issue is that the string within my push looks really awkward and long. What's the better way of doing this?


2 Answers 2


I have a few issues with your code before I get into your actual question:

  • Your indentation is inconsistent and wrong, you should be using two or four space indentation, not three-space indentation.
  • Your usage of quotation marks is inconsistent, use either " or ', but stay consistent.
  • BUG: you're missing a close html tag character in here: <div class="card waves-effect waves-block waves-light"</div>.
  • Instead of pushing it into the block as one big lump, consider pushing it through at each category, that way it'll actually look like it's loading, and you can avoid storing a massive html string. You can use jQuery's .append to do this

As for your specific question, I would style it better by splitting it into parts, and joining each part like so:

$.getJSON('/api/get_categories', function(data){
    $.each(data.categories, function(key, value){
            '<div class="card">' +
            '<div class="card waves-effect waves-block waves-light"></div>' +
            '<div class="card-content">' +
            '<span class="card-title activator grey-text text-darken-4">' +
            value + '</span></div></div>'
  • \$\begingroup\$ Thank you! This is way more than what I asked for, but thank you for pointing out all of those issues. \$\endgroup\$ Jan 17, 2016 at 23:58

I would use a templating engine like underscore to keep all your markup separate.

  • \$\begingroup\$ Please add more to your post. Why would you suggest this? Why is this better than what the OP is doing? Your post is very thin right now and is likely to be deleted. \$\endgroup\$
    – SirPython
    Jan 16, 2016 at 22:53
  • \$\begingroup\$ Sounds like a perfectly reasonable answer to me, but could use some more explaination. Maybe an example. \$\endgroup\$
    – RubberDuck
    Jan 17, 2016 at 0:39
  • \$\begingroup\$ @RubberDuck I can't find a source, but I remember a meta post where we discussed "generic suggestion without reason, explanation, example, or making it clear the poster read the question at all" not making a valid answer. \$\endgroup\$
    – anon
    Jan 17, 2016 at 23:13

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.