javascript - Insert select element using innerHTML (JS) -



javascript - Insert select element using innerHTML (JS) -

i'm trying replace content in td tag id "row2".

can tell me why innerhtml line not working?

var e = document.getelementbyid("location"); //location <select> id var area = e.options.selectedindex; if (area == 1) { var myrow = document.getelementbyid("row1"); var array = ["item1", "item2", "item3"]; var selectlist = document.createelement("select"); selectlist.setattribute("id", "myselect"); document.getelementbyid("row2").innerhtml = selectlist (var = 0; < array.length; i++) { var alternative = document.createelement("option"); option.setattribute("value", array[i]); option.text = array[i]; selectlist.appendchild(option); } }

you need utilize appendchild insert new element kid of element.

innerhtml html text within element, should not assign element it.

just instead:

document.getelementbyid("row2").appendchild(selectlist);

you can clear before appending kid setting innerhtml "", count 2 updates dom , browser may repaint or recompute page 2 times instead of one.

a improve solution replace kid in single step, using replacechild method:

var row2 = document.getelementbyid("row2"); if (row2.childnodes.length > 0) { /* there kid attached element, replace */ row2.replacechild(selectlist, row2.childnodes.item(0)); } else { /* there no kid attached element, append */ row2.appendchild(selectlist); }

these functions part of node interface documented w3c, check out: interface node

javascript html select innerhtml

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -