0

I have a list of table columns. I would like to display them in one row.

What am I trying is :

for (var i = 0; i < key.length; i++) {
    writeToScreen3('<div class="col-sm">' + key[i] + '</div>'); //column name
}
function writeToScreen3(message) {
    var pre = document.createElement("p"); //I realize I am creating another element <p> How to do it diffrently?
    pre.innerHTML = message;
    output.appendChild(pre);
}

What I need is this transferred to JavaScript :

<div class="container">
  <div class="row">
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
    <div class="col-sm">
      One of three columns
    </div>
  </div>
</div>

What I also tried :

function test8() {
    $("#output").html('<div class="container">< div class= "row" >'); //but it always closes these 2 divs here . I want it not to close it. output is a div field
}
3
  • where is output? are you mixing <p> with <pre>? Commented Sep 16, 2020 at 15:15
  • output is <div id="output"> Commented Sep 16, 2020 at 15:17
  • How can I not createElement for example? Or just place <div> tags without closing them, then display columns names, and then close it? Commented Sep 16, 2020 at 15:19

1 Answer 1

1

You can do something like this:

function createContainer(columns) {
  function createDivWithClass(cls) {
    const div = document.createElement('div');
    div.classList.add(cls);
    return div;
  }

  const container = createDivWithClass('container');
  const row = createDivWithClass('row');

  container.appendChild(row);

  for (let i = 0; i < columns.length; i++) {
    const column = createDivWithClass('col-sm');
    column.textContent = columns[i];

    row.appendChild(column);
  }

  return container;
}

const container = createContainer([1, 2, 3, 4]);

document.getElementById('output').appendChild(container);

console.log(container.outerHTML);
<div id="output"></div>

Here, I've defined a function called createDivWithClass to make it easier to create a <div> and set a class name to it.

Then, I'm using this function to create a <div class="container">, create a <div class="row"> and add that to the container, and then go through the columns array and create <div class="col-sm"> and add those to the row element.

Just like you can append elements to the #output element in the DOM, you can also append elements to elements that you've created and are not yet in the DOM.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.