Clay H
Clay H

Reputation: 31

jQuery Create Div with Elements

I used document.createElement to create a div with a class like this:

var newDiv = document.createElement("div");
newDiv.className = 'note';

But i don't know how to get the div to have the html elements of .note and every time I trigger the block, it doubles however number of notes there are! So if there were 4 notes, it would create 4 notes, resulting in 8 notes:( (.note is the div I'm copying)

here is the full code:

HTML:

<div class="note">
  <input id="subject" value="SUBJECT"></input>
  <div class="time"></div>
  <hr>
  <ul>
      <li>
          <input type="text" value="TYPE HERE"></input>
      </li>
  </ul>
</div>

CSS:

.note {
    padding:10px;
    background-color:#FFFF19;
    height:400px;
    width:400px;
    border-radius:1px;
    display:inline-block;
    margin:5px;
}
input {
    background-color:#ffff19;
}
#subject {
    background-color:#ffff19;
    border:none;
    width:73px;
}
.time{
    height:25px;
    width:300px;
    float:right;
}

.note hr{
    width;350px;
}

JS:

$('#wrp').click(function newNote() {
    var newDiv = document.createElement("div");
    newDiv.className = 'note'
    var currentDiv = document.getElementById("wrp");
    $(newDiv).insertBefore('.note');
}

Upvotes: 1

Views: 166

Answers (2)

Praxis Ashelin
Praxis Ashelin

Reputation: 5227

You can use the .html() function to retrieve or replace the inner HTML (all the elements) of a div:

var noteHtml = $(".note").html(); //Retrieve all HTML / elements inside the .note div
var newDiv = document.createElement("div");
newDiv.className = 'note';
newDiv.html(noteHtml); //Place all the HTML / elements in the new div

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

Or you could simply clone() the .note element you want to copy.

$('#wrp').click(function() {
    var note = $('.note').first(); // assuming the first .note to clone
    note.clone().insertBefore(note);
});

Upvotes: 4

Related Questions