javascript - Creating parent and child elements wit Js/jQuery -
i'm beginner @ js/jquery. want code structure 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 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 fiddle: https://jsfiddle.net/ds6wj38k/2/
i found few similar questions , tried add code can't adjust.
thanks.
so first of need div
class box
:
var box = $('<div>').addclass('box');
then want p
number:
var p = $('<p>').text(1);
and div
class content
, span
inside:
var content = $('<div>').addclass('content'); var span = $('<span>').text('any'); content.append(span);
so created elements need. time combine them:
var listitem = box.append(p).append(content);
and add body
!
$('body').append(listitem);
the final code:
function adddivs(n) { (var = 1; <= 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
Comments
Post a Comment