1

I am trying to output html with jQuery.

$('body').append('
<div>
  <div>
    <div></div>
  </div>
</div>
');

I want to indent the code in this way for higher readability. It works for php but not in JS, any ideas? I use notepad++ as editor.

1
  • 1
    what do you mean by it's not working in JS ? Commented Mar 26, 2011 at 19:30

5 Answers 5

5

You should be using a templating system for that. No matter how much indentation you use, if you mix to much HTML and Javascript you will end-up will spaghetti code.

HTML

<script type="text/template" id="my-template">
    <div>
        <div>
            <div></div>
        </div>
    </div>
</script>

Javascript

$('body').append($('#my-template').html());

If you need more control over your template rendering, you need to use a library. I recommend underscore.js, its not the best templating engine for javascript, but it's very lightweight and comes with a great set of helper functions.

Sign up to request clarification or add additional context in comments.

Comments

3
$('body').append('\n\
<div>\n\
  <div>\n\
    <div></div>\n\
  </div>\n\
</div>\n\
');
  • The \n is to insert a newline character in your string (so it’ll get outputted in your body element)
  • The final \ is Javascript's line continuation character, so you can keep your JS code indented without having to add + '' everywhere.

Comments

1

Try something like this:

$('body').append('\
<div>\
  <div>\
    <div>foo</div>\
  </div>\
</div>');

Comments

0

Have you tried using the Javascript string literals? "\n" is a newline, and "\t" is a tab.

Comments

0

If you want to indent, I suggest using the concatenation operator "+" whenever you want to add a new line in your code:

$('body').append(
'<div>' +
  '<div>' +
    '<div></div>' +
  '</div>' +
'</div>'
);

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.