Can't change divs ID of first element from <tempate>

Viewed 48

I have this HTML template:

<template id="single_feed">

    <div class="ibox" id="FIRST_DIV">
        <div class="ibox-title">
            <h5 id="naslov"></h5>
         </div>
        <div class="ibox-content">
            <form method="get" _lpchecked="1">
                 <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label>
            </form>
        </div>
    </div>
</template>

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;    

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});     

P.S: I removed unnecessary parts to make code more readable.

3 Answers

Hope this will helps, const template = (document.getElementsByTagName("template")[0]).content.cloneNode(true); const firstDiv = template.querySelector("div"); firstDiv.id = "new id"; document.body.querySelector('#kolona_1').appendChild(firstDiv);

Try something like below

   $(".btn-RSS-single").click(function(e) {
    var idClicked = e.target.id;    

    const $template = $( $('#single_feed')[0].innerHTML );

    $template.find("div:first").attr("class", "template-new"+idClicked);

    $('#kolona_1').append($template);
    $('#kolona_1').find('.template-new' + idClicked).attr('id', 'NEW_ID_' + idClicked);

});

jQuery has .html() function to retrieve the inner html and .clone() function to clone the element. You can use both to achieve what you want and make the code more readable.

See this example (I have changed some values to make the example clearer):

let clicked = 0;

$(".btn-RSS-single").click(function(e) {
  var idClicked = e.target.id;
  idClicked = clicked++;

  const template = $("#single_feed").html();
  $template = jQuery(template).clone().attr("id", "NEW_ID_" + idClicked);

  $('#kolona_1').append($template);
});
#kolona_1 {
  border: 1px solid gray;
}

#kolona_1 > div {
    background-color: rgba(180, 180, 180, 0.2);
    margin: 1em;
  }

.btn-RSS-single {
  background-color: lightblue;
  padding: 0.2em 1em;
  text-align: center;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="kolona_1"></div>
<div class="btn-RSS-single">ADD</div>
<template id="single_feed">
  <div class="ibox" id="FIRST_DIV">
    <div class="ibox-title">
      <h5 id="naslov"></h5>
    </div>
    <div class="ibox-content">
      <form method="get" _lpchecked="1">
        <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label></div>
      </form>
    </div>
  </div>
</template>

Related