Özkan Özkan - 28 days ago 6
HTML Question

Creating parent and child elements wit Js/jQuery

I'm beginner at js/jquery.
I want to code this structure with js/jquery:

<div class="box">
<p>1</p>
<div class="content"><span>Lorem</span></div>
</div>

<div class="box">
<p>2</p>
<div class="content"><span>Ipsum</span></div>
</div>

<div class="box">
<p>3</p>
<div class="content"><span>Dolor</span></div>
</div>

<div class="box">
<p>4</p>
<div class="content"><span>Sit</span></div>
</div>

<div class="box">
<p>5</p>
<div class="content"><span>Amet</span></div>
</div>


I have this code:

function addDivs(n) {

for(var i=1; i<=n; i++) {

var parentP = $("<p>"+i+"</p>");
var parentContent = $("<div class='content'></div>");

var boxClassDiv = document.createElement("div");
document.body.appendChild(boxClassDiv);
boxClassDiv.setAttribute("class", "box");
$("body").prepend(boxClassDiv, [parentP, parentContent]);
}
}

window.onload = function getFuncs() {
addDivs(16);
}


Here is fiddle: https://jsfiddle.net/ds6wj38k/2/

I've founded a few similar questions like this and tried to add to my code but i can't adjust.

Thanks.

Answer

So first of all you need a div with class box:

var box = $('<div>').addClass('box');

Then you want a p with a number:

var p = $('<p>').text(1);

And finally a div with class content and span inside:

var content = $('<div>').addClass('content');
var span = $('<span>').text('any');
content.append(span);

So you created elements you need. Time to combine them:

var listItem = box.append(p).append(content);

And add to body!

$('body').append(listItem);

The final code:

function addDivs(n) {
  for (var i = 1; i <= n; i++) {
    var box = $('<div>').addClass('box');
    var p = $('<p>').text(i);

    var content = $('<div>').addClass('content');
    var span = $('<span>').text('any');
    content.append(span);

    var listItem = box.append(p).append(content);

    $('body').append(listItem);
  }
}

window.onload = function getFuncs() {
  addDivs(16);
}

Check out code online: http://jsbin.com/xeyugubefu/edit?js,output

enter image description here

Comments