hodgesaargh
hodgesaargh

Reputation: 110

JQuery append and Javascript appendChild with document.write in appended Element

I am a bit confused about how differently the jQuery append() and the Javascript appendChild() functions handle an Element that calls the document.write() function within.

Here's my HTML Code:

<div id="main-area">
</div>

<div id="temp-area">
    <div id="content">
        <script>
            document.write('Lorem Ipsum Dolor...');
        </script>
    </div>
</div>

I basically want to put the whole Element '#content' and all its Contents, including the 'Lorem Ipsum' Javascript Bit from '#temp-area' to '#main-area'. My first approach was simple jQuery:

target = jQuery('#main-area');
content = jQuery('#content');
target.append(content);

This works, but with one exception: the 'Lorem Ipsum Dolor' text is written once in the '#content' Element where it belongs, now within the '#main-area' div, AND once beneath both divs at the bottom of the page (without the '#content' div wrapping the text). Of course, I want the text to be shown only once, within the '#content' div. If I write the Lorem Ipsum text as static HTML, the whole thing works just fine, so it's got to have something to do with the document.write function and how this affects the DOM Tree, right? So i experimented a little more and came to this solution:

target = jQuery('#main-area').get(0);
content = jQuery('#content').get(0);
target.appendChild(content);

With this Code, the Lorem Ipsum Text is only written once in the HTML Document, and exactly where i want it to be. Problem solved.

But i don't get how and why this approach works and the other one doesn't. So I'm not asking for a solution to my problem, but for an explanation as to why both approaches handle things so differently to understand whats going on here. Is there perhaps a wholly different solution to the scenario that I'm missing and that's easier to understand?

(i tested in firefox and opera)

Thanks

Upvotes: 2

Views: 4771

Answers (2)

Paul Grime
Paul Grime

Reputation: 15104

Please read this question and answer.

Basically, the <script> needs to be added to the DOM directly to be executed via appendChild. So I guess as a child of another element this won't work. But if added through jQuery, then jQuery will manage any script content itself and make sure it gets executed. See jQuery source and search for

clean: function( elems, context, fragment, scripts ) {

This is a function that strips <script> tags out, and they ultimately will be executed by jQuery.

Here's a small jsfiddle demo of options.

Upvotes: 1

AlexBay
AlexBay

Reputation: 1313

You don't need jQuery for this behaviour.

Simply use JavaScript DOM functions:

var target = document.getElementById('main-area'),
    content = document.getElementById('content');

target.appendChild(content);

You can see it working Here

Upvotes: 1

Related Questions