Amirhossein Amirhossein - 10 days ago 6
Javascript Question

appendChild odd behavior in javascript

In the procedure of creating and appending elements to a webpage, I faced an odd behavior of javascript, that is replacing a child with another instead of appending. here is the code:

var window = document.createElement("div"); //the minesweeper game window
window.setAttribute("class", "window");
document.body.appendChild(window);

var title_bar = document.createElement("div");//the title bar of the window
title_bar.setAttribute("class", "title-bar");
window.appendChild(title_bar);

var game_title = document.createElement("span");//the title of the game
game_title.setAttribute("id", "game-title");
game_title.innerHTML = "Minesweeper Online - Beginner!";
title_bar.appendChild(game_title);

var right_corner_div = document.createElement("div");// right corner buttons
title_bar.appendChild(right_corner_div);

var btn_minimize = document.createElement("span");//the minimize button
btn_minimize.setAttribute("class", "btn");
btn_minimize.setAttribute("id", "btn-minimize");
btn_minimize.innerHTML = "-";
right_corner_div.appendChild(btn_minimize);

var btn_close = document.createElement("span");//the close button
btn_close.setAttribute("class", "btn");
btn_close.setAttribute("id", "btn-close");
btn_close.style.marginLeft = "3px";
btn_close.innerHTML = "×";
right_corner_div.appendChild(btn_close);

var top = document.createElement("div");//top of window div, underneath the title bar
title_bar.setAttribute("class", "top");
window.appendChild(top);


but unlike what I expect to see as the result, the latest div with the class attribute of top replaces the first div with the class attribute of title-bar. why does this happen?

Answer

You have title_bar here instead of top (second last line in your question):

var top = document.createElement("div");
*title_bar*.setAttribute("class", "top");
window.appendChild(top);

Replace that with top and it should work.

By the way, don't name a variable window in a browser, since that is what the global object reference is assigned to. Call your variable game_window or something else along those lines instead.

Also you probably don't care about the actual HTML class attribute of your elements and should set the className property directly instead:

top.className = "top"; // instead of top.setAttribute("class", "top");