jQuery bug when trying to insert partial elements before() / after() ?

Posted by RedGlobe on Stack Overflow See other posts from Stack Overflow or by RedGlobe
Published on 2010-12-21T17:34:11Z Indexed on 2010/12/21 17:54 UTC
Read the original article Hit count: 155

Filed under:
|

I'm trying to wrap a div around an element (my 'template' div) by using jQuery's before() and after(). When I try to insert a closing after the selected element, it actually gets placed before the target.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Div Wrap</title>

<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>

<script>
$('document').ready(function() {
    var beforestr = "<div id=\"wrap\"><div id=\"header\">Top</div><div id=\"page\">";
    var afterstr = "</div><div id=\"footer\">Bottom</div></div>";
    $('#template').before(beforestr);
    $('#template').after(afterstr);
});
</script>

</head>
<body>

<div id="template">
    <h1>Page Title</h1>
    <p>Pellentesque habitant morbi tristique senectus 
    et netus et malesuada fames ac turpis egestas. Mauris 
    placerat eleifend leo. Quisque sit amet est et sapien 
    ullamcorper pharetra. 
    <script>document.write('This script should still work and might contain variables. Please don\'t recommend concatenation.');</script> 
    Donec non enim in turpis pulvinar facilisis.</p>
</div>

</body>
</html>

The result is:

<div id="wrap">
    <div id="header">Top</div>
    <div id="page">
    </div>
</div>
<div id="template">
    <h1>Page Title</h1>
        <p>Pellentesque habitant morbi tristique senectus 
        et netus et malesuada fames ac turpis egestas. Mauris 
        placerat eleifend leo. Quisque sit amet est et sapien 
        ullamcorper pharetra. 
        This script should still work and might contain variables. Please don't recommend concatenation.
        Donec non enim in turpis pulvinar facilisis.</p>
</div>
<div id="footer">Bottom</div>

Why are my closing wrap and page divs getting placed before the target, when I'm trying to place them after() ? Is there an alternative way to accomplish this (keeping in mind I may need to call script functions within the template div)?

As I'm sure you're aware, best practices aren't what I'm going for here.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery