How to save an HTML fragment and paste it later in the document?

Is there a way to save an HTML fragment in a variable using Javascript or jQuery? (obviously this is a non-working example)

var mysnippet = << EOF
<div class="myclass">
  <div class="anotherclass">
    Some dummy text
  </div>
</div>
EOF

And then paste it into the document using jQuery:

mysnippet.append($('#someelement'));

EDIT:

Please read this before replying to the comment: I have an HTML fragment inside my JS file and I need to save it in a Javascript variable using something like this EOF construction. I need to avoid putting it between quotation marks.

If this is not possible using Javascript and / or jQuery, then the question has no solution.

+5
source share
7 answers

javascript, ejs haml-coffee,...

+1

HTML- div, , var content = $('#somediv').html();, div ! $('#otherdiv').append(content);

$().html(); HTML div. : http://api.jquery.com/html/

$().append(<content>); div. documentatoin: http://api.jquery.com/append/

+4

:

var mysnippet = "<div class='myclass'>"+
  "<div class='anotherclass'>"+
    "Some dummy text"+
  "</div>"+
"</div>";

append ( ).

+1

.

JavaScript

var html = '<b>Bold</b>'
$('.anotherclass').append(html);

HTML

<div class="myclass">
  <div class="anotherclass">
    Some dummy text
  </div>
</div>
0

, << EOF . :

$el = $('<div />')
  .addClass('myClass')
  .append(
    $('<div />')
      .addClass('anotherclass')
      .text('Foo Bar')
  );
0

Thinking of the same question, I found this discussion. What I have in mind is to put a hidden textareaone containing html and then extract the html from there.

Thus, there will be no conflicts with doubled DOM identifiers, since the textareacontent is not displayed as html.

0
source

For those who come across this, like me ... You can use the new one <template> in HTML5. Unfortunately, it still does not store HTML in JavaScript :(

0
source

All Articles