Home Ask Login Register

Developers Planet

Your answer is one click away!

anonymousCoder February 2016

Dynamic creating elements using javascript

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";


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.


jfriend00 February 2016

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


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.

Post Status

Asked in February 2016
Viewed 2,275 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life