tags:

views:

56

answers:

2
<body>
  <div id="outer">
    <script>var e = document.createElement("div");
            e.id = "inner1";
            document.body.appendChild(e);</script>
    <script>document.write("<div id='inner2'></div>");</script>

The structure I want would be: html>body>div#outer>div#inner1+div#inner2

the structure I get is: html>body>(div#outer>div#inner2)+div#inner1

A: 

Look into the jquery documentation. Jquery is a javascript library that you include in your page header. It provides a ton of useful methods for working with the DOM. jQuery is my first choice for writing javascript these days. Straight up js just feels old school to me now. Knowing how to use jQuery effectively (or at least some js library) is a skill every web developer should have. jQuery provides methods like $('css-selector-here').append('what you want to insert'), .prepend(), .insertBefore(), insertAfter(), and .html(), among many others, one of which would probably suit your needs.

Here is a list of all the DOM manipulatuion methods: http://api.jquery.com/category/manipulation/

Adam
Thanks, I know about jQuery, this doesn't answer the question though. jQuery doesn't help in this situation unless there is a "last-descendant-of" that I don't know about but that seems far-fetched and inefficient.
Joe Flateau
I tried: var c = document.body; while (c.hasChildNodes()){ c = c.lastChild; }
Joe Flateau
That doesn't work either, the node isn't added to document until it is completed.
Joe Flateau
Why would jQuery magically be able to do this?
Tim Down
+1  A: 
lincolnk
Yes, siblings. That's zen-coding syntax.
Joe Flateau
This doesn't accomplish what I wanted, I want to eliminate the "document.write" call, not make it more complicated.
Joe Flateau
well I read the title wrong and everything's downhill from there. i'll look again.
lincolnk
If I'm not mistaken `document.getElementById('outer').appendChild(inner2)` will not work if it have to be the place where code is executing - DOM is not ready. Safer way should be to wrap it into function and execute as `body.onload`
dev-null-dweller
@lincolnk, now your code is the same as my example. @dev-null-dweller, you're right, the element isn't in the DOM yet. I think what I'd have to do to make it work is document.write an element with an id and replace or append to that after the DOMReady or load event.
Joe Flateau
yours http://jsbin.com/adosa3 and mine http://jsbin.com/idefi3 they're different.
lincolnk