meep
meep

Reputation: 23

how to make a new div with jquery?

okay so, I need to create a new div using jquery with the information of a first and last name that I loop from my array.. This is what I have so far, I was wondering if I could get some help on how to make it show up on my webpage. it needs to show up like:

hello firstname lastname 
hello firstname lastname
hello firstname lastname
<div id="output"></div>
function names() {
         var firstAndLast = [
              {name: "jane", surname: "doe"},
              {name: "john", surname: "leg"},
              {name: "hunny", surname: "bun"}

            ];

        var div = $("#output");
            for (var i=0; i < firstAndLast.length; i++) {

        }

          var div1 = $("<div>").html("Hello name surname");
                 $("#names").append(div1);

Upvotes: 1

Views: 54

Answers (2)

Shubham Dixit
Shubham Dixit

Reputation: 1

You can try something like this

function names() {
  var firstAndLast = [{
      name: "jane",
      surname: "doe"
    },
    {
      name: "john",
      surname: "leg"
    },
    {
      name: "hunny",
      surname: "bun"
    }

  ];


  let _data = firstAndLast.reduce((acc, {
    name,
    surname
  }) => {

    acc += `hello <span>${name}</span> <span>${surname}</span><br>`
    return acc;
  }, "")


  $("#output").html(_data);

}

names()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
</div>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your code is almost there. The main issue is that you need to put the line of jQuery which creates the div and appends it within the for loop. In addition you can retrieve the name and surname from the objects in the array using the i variable to access them by index:

var $output = $("#output");
for (var i = 0; i < firstAndLast.length; i++) {
  var div1 = $("<div>").html(`Hello ${firstAndLast[i].name} ${firstAndLast[i].surname}`);
  $output.append(div1);
}

That being said, the most performant way to do this would be to use map() to build an array of HTML strings which you only append to the DOM once:

function names() {
  let firstAndLast = [
    { name: "jane", surname: "doe" }, 
    { name: "john", surname: "leg" }, 
    { name: "hunny", surname: "bun" }
  ]; 

  let html = firstAndLast.map(o => `<div>Hello ${o.name} ${o.surname}</div>`);
  $("#output").append(html);
}

names();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output"></div>

Upvotes: 1

Related Questions