javascript - How can I append elements with iterating attributes? -


i wrote script isn't behaving intended. contains object supposed produce paragraph element, can assigned text of it's own creation iteration, appending each new element until loop converges. purposes of highlighting approach, have emulated loop iteration manually, removing unnecessary confusion.

var myelement=document.createelement('p');    myelement.setattribute('id','one');  document.body.appendchild(myelement);  document.getelementbyid('one').innerhtml='one';    myelement.setattribute('id','two');  document.body.appendchild(myelement);  document.getelementbyid('two').innerhtml='two';

as can see, result produces single element instead of two, strange because iterated append line @ least twice, , element contains text specified in second iteration.

what doing wrong?

make it

var myelement=document.createelement('p');  myelement.setattribute('id','one'); document.body.appendchild(myelement); document.getelementbyid('one').innerhtml='one';  myelement=document.createelement('p'); //this new line added myelement.setattribute('id','two'); document.body.appendchild(myelement); document.getelementbyid('two').innerhtml='two'; 

basically making changes in same element instead of creating new element.

for making multiple paragraphs in loop

function makenewparagraph(id, text) {     var myelement=document.createelement('p');     myelement.setattribute('id',id);     document.body.appendchild(myelement);     document.getelementbyid('one').innerhtml=text;     return myelement; } var numarray = [ "one", "two", "three", "four", "five" ]; numarray.foreach( function(value){   makenewparagraph(value, value); } ); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -