11

Right now Facebook wants me to throw this ugly div at the top of my page directly under <body>

<div id="fb-root"></div>

I would like to avoid this by instead, appending it via JavaScript.

.append('<div id="fb-root"></div>');

This places it at the bottom of the page.

</head>
<body>
    <header>test</header>
    <div id="fb-root"></div>
</body>

How can I 'append' it to the top?

</head>
<body>
    <div id="fb-root"></div>
    <header>test</header>
</body>
O P
  • 2,327
  • 10
  • 40
  • 73
  • possible duplicate of [javascript: how to append div in "begining" of another div](http://stackoverflow.com/questions/15110484/javascript-how-to-append-div-in-begining-of-another-div) – Felix Kling May 01 '13 at 22:02
  • I am curious - why is it that you want to do this via JavaScript? The element is going to end up in your DOM/markup either way. – jamauss May 01 '13 at 22:03
  • @jamauss, I'm fine with it ending up in my DOM for further manipulation; but I'm not okay with it going in front of my `header` tag. I strongly believe in following W3C structure standards. – O P May 01 '13 at 22:04
  • That still doesn't really explain why you want to do it via JavaScript instead of just putting it in the document manually. Why can't you put it where you want without JavaScript? – jamauss May 01 '13 at 22:11
  • @jamauss, I *can* put it where I want to without JavaScript. I want to do it with JavaScript so it does not interfere with my perfected HTML structure. – O P May 01 '13 at 22:19
  • ahhh, ok then. I guess I get that. – jamauss May 01 '13 at 22:21

3 Answers3

31

Use prepend method:

$('body').prepend('<div id="fb-root"></div>');
Ram
  • 143,282
  • 16
  • 168
  • 197
1

You can use

$('#fb-root').detach().insertBefore('body>*:first');
Milap
  • 6,915
  • 8
  • 26
  • 46
Hinovska
  • 11
  • 3
-3

You can do this without JQuery and without prepend

<body>
    <header>test</header>
</body>
<script>
    document.body = '<div id="fb-root"></div>' + document.body + "</div>";
</script>
Tigran
  • 1
  • 2
    _“You can do this without JQuery and without prepend”_ — True: you’d use `document.body.prepend(Object.assign(document.createElement("div"), { id: "fb-root" }));`. Rewriting the `` kills all event listeners bound to it and that part of the DOM has to be reparsed, so don’t do it. See [Is it possible to append to innerHTML without destroying descendants' event listeners?](https://stackoverflow.com/q/595808/4642212). – Sebastian Simon Oct 11 '20 at 19:57