Get Html Code, replace parts and store in variable as string without changing the DOM Element

Viewed 455

i have a DOM Element

<div class="list-item">
  <div class="name"></div>
  <div class="id" data-id=""></div>
  <a href="">Link</a>
</div>

I want to get the HTML like $('.list-item').html(); Then i want to fill parts like data-attributes and content with own variables so i can get for example this:

<div class="list-item">
  <div class="name">NAME CONTENT</div>
  <div class="id" data-id="123456">CONTENT</div>
  <a href="https://link.de">Link</a>
</div>

Then i want to store that as string in a varibale like

var htmlCode = '<div class="list-item">.....';

The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!

3 Answers

You can use .clone() to clone your div and then use .attr() to change attr from id class .

Demo Code :

var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
  <div class="name"></div>
  <div class="id" data-id=""></div>
  <a href="">Link</a>
</div>

You can use this

<script>
    var html = $('.list-item').html();
    console.log(html);

    var list = $('<li></li>')

    $('.list-item').children().each(function(index,elem){  
        $(list).append($(elem).clone());
    })
    $(list).children().each(function(i,e) {
        $(e).data("id","1234")
        $(e).html("ll");
    })
    console.log($(list).children());
</script>

Thank you all. With your help i got this solution:

var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');

So $code is my varibale wich stores the html as string without changing the DOM Element :)

Related