Amirhossein Amirhossein - 8 months ago 52
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");

var title_bar = document.createElement("div");//the title bar of the window
title_bar.setAttribute("class", "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!";

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

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

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

var top = document.createElement("div");//top of window div, underneath the title bar
title_bar.setAttribute("class", "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 Source

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

var top = document.createElement("div");
*title_bar*.setAttribute("class", "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");