Creating Parent and Child Elements with Js / jQuery

I am starting in js / jquery. I want to encode 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 the fiddle: https://jsfiddle.net/ds6wj38k/2/

I found several similar questions like this, and tried to add to my code, but I canโ€™t configure.

Thanks.

+5
source share
2 answers

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

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

Then you want p with 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 have created the necessary elements. Combination time:

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

And add to the body !

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

End 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 the code online: http://jsbin.com/xeyugubefu/edit?js,output

enter image description here

+1
source

Here's how I suggest doing it:

 function addDivs(words) { words.forEach( function (word, i) { $('body') .append($('<div>').addClass('box') .append($('<p>').text(i+1)) .append($("<div>").addClass('content').append($('<span>').text(words[i])))); }); }; $(function getFuncs() { var words = 'Lorem ipsum dolor sit amet'.split(' '); addDivs(words); }); 

jQuery is designed to support the method chain that the above code demonstrates.

Note that in addition to creating content using jQuery, you must also replace window.onload with a jQuery.ready call, which you can write as $(callback) .

0
source

Source: https://habr.com/ru/post/1259332/


All Articles