0

I am trying to select a child div element from a template that I have cloned. The idea is that I clone the template, and update the id with a unique site ID that is from a database.

My template looks like this, and it is the div with class "site-container" whose id I would like to update:

<template id="base-site-template">
    <div class="site-container">
        <div class="site-minimize">
            <span class="site-minimize-carat" onclick="toggleSiteShow()">&#9650;</span>
        </div>
        <div class="site-sidenav">
            <a href="#!">General</a>
            <a href="#!">Site Resiliency</a>
            <a href="#!">Site Sizing</a>
            <a href="#!">Leased Property</a>
            <a href="#!">Satellite</a>
            <a href="#!">Contacts</a>
        </div>
        <div class="site-bottom-buttons">
            <button class="site-bottom-button get-contacts">Get contacts</button>
            <button class="site-bottom-button claim-site">Claim site</button>
        </div>
    </div>
</template>

I am using the following javascript functions to try to achieve this:

  1. Iterate through the data and clone the template, then append to a container div
function updateNSites(data){
    data["fetched-sites"].map(function(element, index){
        var cloned = cloneTemplate(index);
        console.log(`Processing site ${index}...`);
        $("#fetch-n-sites-demo").append(cloned);
    });
}
  1. Clone the actual template, and update the id with the passed index argument:
function cloneTemplate(index){
    var testClone = $("#base-site-template").clone();
    var siteContainer = $("#base-site-template > div");
    console.log(siteContainer.length);
    console.log("Num of children: " + testClone.children().length);
    console.log(testClone.children()[0]);

    siteContainer.attr("id", index);
    return $(siteContainer);
}

The problem I am seeing is that the console.log calls within cloneTemplate are indicating that no children are being found:

[Console log of "siteContainer.length"] - 0
[Console log of "testClone.children().length"] -  Num of children: 0
[Console log of "testClone.children()[0]"] - undefined

Could I please have some help finding the div with class "site-container"? I am unsure what is wrong with my selectors. Thank you very much

Ian Murray
  • 65
  • 6
  • 1
    Does this answer your question? [How to select elements from – kmoser Jul 08 '22 at 05:32
  • 1
    I ended up going with a different approach - use a div element as the template and set its display to none. Once I've cloned it, change the display to block. – Ian Murray Jul 08 '22 at 16:54

0 Answers0