Dymond
Dymond

Reputation: 2277

AppendChild and InsertBefore

I'm having a little problem with hierarchy elements that are created dynamically.
Been trying to use insertBefore so they change place but no luck, wont get any errors but still I get the element under the other.

I have this function that creates a class called dice-window-wrapper and adds it to the page-content-wrapper.

var outerDiv = createElementWithClass('div', 'dice-window-wrapper'),
innerDiv = createElementWithClass('div', 'dice-menubar-wrapper');
outerDiv.appendChild(innerDiv);
document.getElementById("page-content-wrapper").appendChild(outerDiv);

And I get the print <div class="dice-window-wrapper">...</div>
No problem here.

Then I want to add an unordered list with some <li> tags, using this function:

icon_ul = createElementWithOutClass('ul');
var icon_ul = document.getElementById("page-menu-wrapper").appendChild(icon_ul);

icon_li = createElementWithId('li','icon-dice');
icon_ul.appendChild(icon_li);
document.getElementById("ul");

And the print will be <ul><li id="icon-dice"></li></ul>

The problem as I told is that <div class="dice-window-wrapper">...</div> should be under the string <ul><li id="icon-dice"></li></ul>.

But even if I change the icon_ul function from appendChild to insertBefore, nothing seems to change.

Upvotes: 4

Views: 11856

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

Try this:

document.getElementById("page-menu-wrapper").insertBefore(icon_ul, outerDiv);

insertBefore requires 2 parameters: what to add, and before what you want to add it.

See the documentation here:

var insertedElement = parentElement.insertBefore(newElement, referenceElement);
//   ^ returns         ^add to this element:      ^ this new element, ^ before this existing element.

Okay, so the problem here is, assuming:

document.getElementById("page-menu-wrapper").insertBefore(icon_ul, outerDiv);

There, the parent of outerDiv isn't "page-menu-wrapper". Either replace that line with:

document.getElementById("page-content-wrapper").insertBefore(icon_ul, outerDiv);

Or replace:

document.getElementById("page-content-wrapper").appendChild(outerDiv);
// With
document.getElementById("page-menu-wrapper").appendChild(outerDiv);

Upvotes: 3

Related Questions