Dan Dan - 1 month ago 5
jQuery Question

How to store html structure in variable , jquery

please see the following code

<div class="test" style="color:red">1</div>
<div class="test" style="color:blue">2</div>
<div class="test" style="color:green">3</div>


I need to save this html structure in javascript variable . So that i used the following code

<script>
$(".test").each(function(){
var otext='<div class="test" style="color:'+$(".test").css("color")+';">'+$(".test").text()+'</div>';
});
</script>


but in otext i got
<div class="test" style="color:redbluegreen">123</div>
.
Actually what wrong in my code ? How to store all html structure and style of class test using jquery?

the desired out put is
var otext =<div class="test" style="color:red">1</div><div class="test" style="color:blue">2</div><div class="test" style="color:green">3</div>;


UPDATE :

what happen if the html structure is lite this ?

<div class="test" style="color:red">1<button clss="test-button" value="remove"/></div>


and here i don't want to save this div structure without
<button class="test-button">
.

Answer

You can use .map() to iterate and create an array of string using outerHTML property of each element.

jQuery(function($) {
  var text = $(".test").map(function() {
    return this.outerHTML
  }).get().join('');
  console.log(text)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" style="color:red">1</div>
<div class="test" style="color:blue">2</div>
<div class="test" style="color:green">3</div>

As per comment

jQuery(function($) {
  var text = $(".test").map(function() {
    var elem = $(this).clone();
    elem.find('.test-button').remove();
    return elem.prop("outerHTML").trim();
  }).get().join('');
  console.log(text)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" style="color:red">1
  <button class="test-button" value="remove" />
</div>
<div class="test" style="color:blue">2
  <button class="test-button" value="remove" />
</div>
<div class="test" style="color:green">3
  <button class="test-button" value="remove" />
</div>