Search code examples
javascriptangulardomnodechildren

How to change element's specific children attributes and content after cloning


I've been reading several questions that appear to be similar but didn't find one that resolve my issue or that the suggested solution solved my problem

I have the following html:

<div id="template">
    <div class="section1" id="sec1">                
        <div class="content">
            <img id="sec1-is" *ngIf="!tstEnded" src="assets/images/r1.png" srcset="assets/images/r1@2x.png 2x,assets/images/r1@3x.png 3x" >
            <img id="sec1-if" *ngIf="tstEnded" src="assets/images/r2.png" srcset="assets/images/r2@2x.png 2x,assets/images/r2@3x.png 3x" />
            <div class="audio-controls">
                <button *ngIf="do1()" (click)="act1()" class="control-btn r1-btn" [ngClass]="{'disabled':!r1Enabled()}"></button>
                <button *ngIf="do2()" (click)="act2()" class="control-btn r2-btn" [ngClass]="{'disabled':!r2Enabled()}"></button>
            </div>
            <div class="test-wrapper">
                <span class="test-line">
                    {{eta}}
                </span>
            </div>
            <div class="test-wrapper">
                <div class="test" tst testType="R" (tstGo)="go($event)"></div>
            </div>
        </div>              
    </div>                  
    <div class="section2" id="sec2" style="background-image: linear-gradient(to top, #d0f6f6, rgba(255, 255, 255, 0));">
        <div class="content">
            <div *ngIf="ended">         
                <img *ngIf="!open" class="case1" (click)="case1()" src="assets/images/case1c.svg" />
                <img *ngIf="open" class="case1" src="assets/images/case1.svg" />
            </div>
        </div>
    </div>
</div>

After cloning the template I wish to change the id attribute of section 1 and 2 as well as the src and srcset of section1 images sec1-is & sec1-if and change the

let itm = document.getElementById("template");
let cln = itm.cloneNode(true);

How can I get a specific "nested" element without iterating over all the children and grandchildren of template, searching for the correct tag?


Solution

  • Hope this help:

        var origin, clone, item;
        origin = document.getElementById("template");
        clone = origin.cloneNode(true);
        item = clone.querySelector("#sec1");
        item.setAttribute("id", "sec2");
    

    Overall: Use querySelector on your clone then setAttribute to update.

    Since your img already has id so you can query directly with #sec1-is.

    But in general, with querySelector you can have the query string like #sec1 img. Similar to css selector

    You can learn more here: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector