Search code examples
javascripthtmlappendinnerhtml

Indent created Elements in javascript


So I've used javascript to build up an HTML markup for a component (accordion)

const accordItem = document.createElement("div");
const accordTitle = document.createElement("p");
const accordContent = document.createElement("div");
const accordContentParagraph = document.createElement("p");

All the elements are appended to a container

container.append(accordItem);
accordItem.append(accordTitle, accordContent);
accordContent.append(accordContentParagraph);

In the code, I populate the divs and paragraphs with content. So, an accordion generator of a sort. So the imaginary user can see a preview of how it would look. And also download a text file.

But if I copy the code from developers' tools. Or write it in the file; I see this mess of a markup. Everything is in one line.

<div class="accordionItem"><p class="accordionTitle">This is some content</p><div class="accordionContent"><p>This is additional content! Something Something</p></div></div><div class="accordionItem"><p class="accordionTitle">This is some content, more</p><div class="accordionContent"><p>Moremore</p></div></div>

While not really a problem, I would like to learn why that is. (pretty new at this).

And is there an easy way to make it indented?

like so:

<div class="accordionItem">
    <p class="accordionTitle">This is some content</p>
    <div class="accordionContent">
        <p>This is additional content! Something Something</p>
    </div>
</div>
<div class="accordionItem">
    <p class="accordionTitle">This is some content, more</p>
    <div class="accordionContent">
        <p>Moremore</p>
    </div>
</div>

Solution

  • instead of using create element method. You can assign a variable with html string and just append the string with parent Element using insertAdjacentHTML method.

    Example :

    let accordionElem = 
    `<div id="accordionCont">
      <span id="childElem1">Hi</span>
      <span id="childElem2">Hello</span>
    </div>`;
    
    document.getElementById("parentCont").insertAdjacentHTML("afterbegin",accordionElem);
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <title>InsertAdjacentHTML</title>
    </head>
    
    <body>
      <div id="parentCont"></div>
    </body>
    
    </html>

    MDN DOC