SO-74374686

by David Thomas

HTML

<button type="button" id="add">Add content</button>
<!-- the following element has a CSS custom property defined in the style
     attribute; this could be populated by the server on the back-end, or
     via JavaScript on the front-end: -->
<div class="d-flex" style="--childCount: 2;">
  <div class="col">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry
  </div>
  <div class="col">
    Lorem Ipsum is simply dummy text
  </div>
</div>

CSS

.d-flex {
  display: grid;
  grid-template-columns: repeat(var(--childCount), 1fr);
  gap: 5px;
}

.d-flex .col {
  background: #7adaff;
}

JavaScript

// some utitlities that I'm using to reduce typing, and for convenience:
const D = document,
  create = (tag, props) => Object.assign(D.createElement(tag), props),
  get = (selector, context = D) => context.querySelector(selector),
  // the sample text from which the text-snippets will be added:
  sampleText = [
    "Lorem", "ipsum", "dolor", "sit", "amet,", "consectetur", "adipisicing", "elit.", "Quas", "a", "repellendus", "sit", "libero", "odio", "aut", "eos", "nihil", "nisi", "quisquam", "aspernatur", "ad", "enim,", "possimus", "amet", "expedita", "facilis,", "architecto", "adipisci", "nulla", "eligendi", "incidunt", "iusto", "pariatur", "laudantium,", "qui", "quaerat", "voluptatem", "inventore.", "Nulla", "suscipit", "cumque", "repudiandae,", "eveniet", "reprehenderit", "quidem", "repellat", "necessitatibus", "consequuntur", "dolore", "id", "modi", "laboriosam", "pariatur", "ex", "delectus!", "Nesciunt", "consequatur", "ducimus", "eveniet", "amet!"
  ],
  // the length of the array of words:
  sampleWordCount = sampleText.length,
  // the function for adding new elements/content:
  addContent = () => {
    // caching the element to which content should be added:
    let parent = get('.d-flex'),
    		// taking a number of words from the array of words to create the text:
	      text = sampleText.slice(0, Math.floor(Math.random() * sampleWordCount)).join(' '),
    		// here we use the create() function to create a <div> element:
        div = create('div', {
        	// with the following properties, setting the element's className to 'col':
          className: 'col',
          // setting the textContent to the text we retrieved:
          textContent: text,
        });
    // we append the <div> to the parent .d-flex element:
    parent.append(div);
    // we set the value of the '--childCount' custom property on the parent,
    // to reflect the number of child elements:
    parent.style.setProperty('--childCount', parent.children.length);
  },
  // we...