Skip to main content

Bug Tracker

Side navigation

#9181 closed bug (invalid)

Opened May 09, 2011 03:33AM UTC

Closed May 09, 2011 03:47AM UTC

Last modified May 09, 2011 04:18AM UTC

$.each() fails to iterate properly over custom HTML elements when using replaceWith()

Reported by: Owned by:
Priority: low Milestone:
Component: core Version: 1.6
Keywords: Cc:
Blocked by: Blocking:

When using $.each() to iterate over an array of custom HTML elements, reformatting these elements with .replaceWith() does not work properly. The first iteration is correctly replaced, but the following iterations improperly pass the 'DOMWindow' object to 'this', rather than the 'HTMLElement' object.

<!doctype html>
<html xmlns:custom="">
<script type="text/javascript" src=""></script>

  //get the list of custom elements
  var elems = document.getElementsByTagName('custom:element');

  //iterate over them

    replace each element with a div instead
    the error that is occurring is that after the first element is replaced,
    the following elements' targets are lost, and each is passed as a 'DOMWindow'
    object instead of the correct 'HTMLElement' object

    console.log('about to kill element: ');

    $(this).replaceWith('<div class="customElement"></div>');
    console.log('killed element');

    Check out the console...
Attachments (0)
Change History (4)

Changed May 09, 2011 03:47AM UTC by rwaldron comment:1

component: unfiledcore
priority: undecidedlow
resolution: → invalid
status: newclosed

Because getElementsByTagName returns a live nodelist, as you are replacing items in the list, elements matching the tag "custom:element" are being reduced by one each on each iteration.

live nodelists are notoriously unpredictable, as seen here.

Changed May 09, 2011 03:56AM UTC by rwaldron comment:2

If you copy the nodelist to a plain array that wont be affected by the "live" nature of a getElementsByTagName nodelist it works as expected:

Changed May 09, 2011 04:07AM UTC by comment:3

Got it - thanks!

Changed May 09, 2011 04:18AM UTC by rwaldron comment:4

You're welcome!