Dynamic creating elements using javascript

此生再无相见时 提交于 2020-01-05 13:54:12

问题


So I have created elements in my html using javascript. The only problem is that my button is not showing up. Following is my code:

var search_div1 = document.createElement("div");
search_div1.className = "input-group row-fluid";

var search_div2 = document.createElement("div");
search_div2.className = "span4 offset4";

var search_input = document.createElement("input");
search_input.className = "form-control offset8";
search_input.id = "searchText";
search_input.type = "text";
search_input.placeholder = "Search...";
search_input.style.width = "200px";
search_input.style.marginLeft = "550px";

var search_span = document.createElement("span");
search_span.className = "input-group-btn";
search_span.width = "50px";

var search_button = document.createElement("button");
search_button.type = "submit";
search_button.id = "search";
search_button.name = "search";
search_button.className = "btn btn-flat";
search_button.onclick = myFunction;

var search_icon = document.createElement("i");
search_icon.className = "fa fa-search";

search_button.appendChild(search_icon);
search_span.appendChild(search_button);
search_input.appendChild(search_span);
search_div2.appendChild(search_input);
search_div1.appendChild(search_div2);

Everything else is showing perfectly except for the search_button and I have created buttons like this that work perfectly. Can someone kindly assist me? Thanks in advance.


回答1:


You're using .appendChild() incorrectly. For example, this line of code:

search_input.appendChild(search_span);

Is trying to make a <span> a child of an <input>. That is not legal HTML.

Remember x.appendChild(y) makes y a child of x in the DOM hierarchy.

We can't really advise what the exact right sequence of appending is because we don't know what HTML structure you're trying to end up with. If you show us what you want the DOM hierarchy to look like when you're done, we can help with the proper code to achieve that.



来源:https://stackoverflow.com/questions/35245654/dynamic-creating-elements-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!