0

Is there an option to append an entire HTML code to a variable without using plus operand, each line in a new line or without using push into array.

I want to be able to be to copy paste the code between single quote with the new lines so it will be easier to edit. My first thought is to copy the code into an external file, but I am not sure how to retrieve it in such a way that it will work.

var html = '<div>
              <div>
                some text
              </div>
           </div>';

Another option I thought about, which seem a good one, is to just copy the HTML in jQuery and copy it into another DIV.

This doesn't work. I am open to 3rd party solution, not just that of the native language. Thanks.

Liron Harel
  • 10,819
  • 26
  • 118
  • 217

3 Answers3

1

You can easily append to HTML elements using jquery (I think this is what your after):

HTML:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">Hello</div>
  <div class="inner">Goodbye</div>
</div>

JS:

$( ".inner" ).append( "<p>Test</p>" );

Becomes:

<h2>Greetings</h2>
<div class="container">
  <div class="inner">
    Hello
    <p>Test</p>
  </div>
  <div class="inner">
    Goodbye
    <p>Test</p>
  </div>
</div>

See: http://api.jquery.com/append/

If you want to make multi line strings see: Multi-line string insert using jQuery

Community
  • 1
  • 1
Marty
  • 2,965
  • 4
  • 30
  • 45
  • if it is short it's not a problem. The problem start with a long HTML code with multiple lines. I want to the code to be readable and easily editable. – Liron Harel Aug 04 '14 at 08:56
  • 1
    see http://stackoverflow.com/questions/3115360/multi-line-string-insert-using-jquery – Marty Aug 04 '14 at 08:57
1

Let's say you have the following markup:

<div id="intro">
    <h2>Hello</h2>
</div>
<p>I am a paragraph, and want to be placed inside intro.</p>

You can then use jQuery's appendTo to to copy p's html, and paste it inside #intro

$(function(){
    $('p').appendTo('#intro');
});
Daniel Apt
  • 2,468
  • 1
  • 21
  • 34
1

Some ideas

\n\ newline separator

var html = '<div>          \n\
              <div>        \n\
                some text  \n\
              </div>       \n\ 
           </div>';

Where those \n\ are easily insertable with a multiline-edit in any better text editor.

Using a hidden element

<div id="hidden_1">
    <div>
      <div>
        some text
      </div>
    </div>
</div>

[id^=hidden_]{ display:none; } // CSS for any ID that starts with "hidden_"

var html = $('#hidden_1').html();
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313