replaceWith implementation
Hallo,
in jQuery 1.2.6 is replaceWith(HTML) method is defined as
after(HTML).remove()
It's correct but if in inserted HTML is JS code witch refer some
element ID from inserted HTML then JS may be evaluated on element with
same ID in removed code and not on inserted.
Example
1) original HTML
...
<div id="testId">
<span id="subId"></span>
<script>
$(document).ready(function() {
$('#subId').append('Some HTML');
}
</script>
</div>
...
2) in AJAX callback load new version of 'tesId' element (with other
content) from server
newVersion =
<div id="testId">
<span id="subId"></span>
some text
<script>
$(document).ready(function() {
$('#subId').append('Some HTML');
}
</script>
</div>
and then call raplace it
$('#testId').replaceWith(newVersion);
3) in result the JS code is evaluated on original element because is
called
after() with result
<div id="testId"> -- original
<span id="subId"></span>
<script>
$(document).ready(function() {
$('#subId').append('Some HTML');
}
</script>
</div>
<div id="testId"> -- new version
<span id="subId"></span>
some text
<script>
$(document).ready(function() { -- new evaluated script
$('#subId').append('Some HTML');
}
</script>
</div>
then evaluated new version JS part which find and evaluate on first
(original) 'subId' element and calling remove() remove whole original
element.
What about prefer "before(HTML).remove()" implementation which is
equivalent and works fine in this type of use. Looking at
implemenetation of before/after methods:
before: this.parentNode.insertBefore( elem, this );
after: this.parentNode.insertBefore( elem, this.nextSibling );
'after has 1 operation more -> 'before' can be bit faster.
I don't know how is implemented DOM trees in browsers. If list of sub
elements is like:
1) linked list - no penalty of inserting element to any place (in may
opinion is this right)
2) array list - bit slower inserting item on -1 place
Is this right request for enhancement in next jQuery releases?
In our project we will use before(HTML).remove() since :-(.
Thank's for such great library
Zdenek