html - JavaScript- how to print p element inside div -


i know can static html, want create dynamically, , struggling lot. here want do: have 2 divs.

    <div class="txttile">      </div>     <div class="pinfo">      </div> 

inside each div want have several paragraphs. let's 10, in each div. first div class "txttile" want have title of something, let's titles like, age,country,experience,street etc.in other div class 'pinfo' want contain information corresponds txttitle. like, age 25, experience 10 years etc, taken local storage, have set up. 2 divs next each other, have done css.

for example. left side

<div class="txttile">               `<div class="pinfo">   <p class="styleforp">                   <p class="styleforp">     age                                      25                                          </p>  </p>  </div>                                </div>` 

i happy if can make native js.

there 2 ways can this:

1) can create element , keep appending place

first div element inside want create new element, here rather having class prefer have id based selection of element

var element = document.queryselector('.txttile'); 

create p element , add class it, can add content inside aswell

var pelem = document.createelement('p'); pelem.classname = 'styleforp'; pelem.innerhtml = 'age'; 

append created element inside div

element.appendchild(pelem); 

2) create html template pass values template , create innerhtml , directly put innerhtml parent element

var item = {     name: "my name",     age: 30,     other: "other info" } var template = [];  template.push(     '<div class="row">',         '<span class="name-info">' + item.name + '</span>',         '<span class="age-info">' + item.age + '</span>',         '<span class="other-info">' + item.other + '</span>',     '</div>' );  var htmlstring = template.join(''); var element = document.queryselector('.txttile'); element.innerhtml = htmlstring; 

if going add lot of items second approach lot better, creating single element , appending them dom tree quite slow, passing whole html string.


Comments