0

So I need to get an array of values rendering in a selection of divs, could anyone help me as to the best way to tackle this?

I have to use javaScript.

6
  • 4
    What did you already tried? Do you have example data of which values in what kind of divs? Commented May 31, 2017 at 15:13
  • 1
    Can you use jQuery or it's just with JavaScript ? Commented May 31, 2017 at 15:16
  • Hi, sorry for being brief. Yeah ideally if it could be in jQuery that would be the best option. Commented May 31, 2017 at 15:29
  • @BasvanDijk So it will just be a standard array and they just have to be popped in a div element. Commented May 31, 2017 at 15:31
  • @AlixEisenhardt Hi, sorry for being brief. Yeah ideally if it could be in jQuery that would be the best option. Commented May 31, 2017 at 15:40

1 Answer 1

1

You can add DOM elements with JavaScript by creating the element you want, setting the properties/attributes as you desire, and then appending them to the DOM (either directly to the body, or to a containing element), like so:

var arr = ["text1", "text2", "text3"];
var container = document.getElementById("container");
arr.forEach(function (text) {
  var div = document.createElement("div");
  div.innerText = text;
  div.classList.add("div-added");
  container.append(div);
});
.div-added {
  padding: 10px;
  border: 2px solid #333;
}
<div id="container"></div>

Alternatively, you can use jQuery, like so:

var arr = ["text1", "text2", "text3"];
var container = $("#container");
arr.forEach(function(text) {
  var div = $("<div>", {
    text: text,
    class: "div-added"
  });
  container.append(div);
});
.div-added {
  padding: 10px;
  border: 2px solid #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

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

1 Comment

So helpful @mhodges

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.