0

I would like to create a reuseable html block using documentFragment. The idea is to create and fill a block of html code similar to below, for every object in an existing array. I'm not worried about filling the inner html yet, for now I just want to build a nested hierarchy.

<div class="container">
    <div class="titleABC">
        <h2 class="abc"></h2>
        <h2 class="efg"></h2>
        <h2 class="xyz"></h2>
        ...
        ...
        ...
        ...
    </div>
</div>

I've add the code I was working on to a js Fiddle.

I could not get more than one element to work in the document Fragment and was wondering if this is possible. Or if there is a better way to accomplish this, a steer in the right direction would be appreciated.

Ultimately I want to be able to add code like... line 16, 17, 18, 19 in my js fiddle, and have a code block generated simply from having added it to the array.

Thank you in advance for time you waste helping me with my nonsense.

Lucas
  • 13
  • 2
  • yes, a documentFragment can contain any HTML - your fiddle adds 4 elements to the fragment, and they get added to the body - what's the issue – Bravo Apr 24 '22 at 02:30
  • also: you could `newDiv.classList.add(blaster.classID)` in the forEach, so you won't need the second loop - but still, what you're claiming happens, does not – Bravo Apr 24 '22 at 02:38
  • you could also add `blaster.el = newDiv;` then you wouldn't need all those `let x =document.querySelector('.x');` ... since the `blastersAry` would hold each blaster, and each blaster would have a reference to the element created for it – Bravo Apr 24 '22 at 02:41
  • I was able to do what I wanted without documentFragment in [this js fiddle](https://jsfiddle.net/LouKaz/m6t0ny1r/21/). But I was unable to create a nested structure using documentFragment. My question is how is this possible with documentFragment as I get errors when i try to create nested html elements. – Lucas Apr 24 '22 at 18:43

0 Answers0