Swap the order of the push_content and replace_with lines, then it will work.

Explanation:

The error you're getting is because the push_content operation rips the img element out of the original document tree, and adds it to the new stand-alone a element instead.

So by the time you try to call replace_with (during the first iteration of the foreach loop), your tree data looks like this:

html <-- $root '-- body +-- h2 | <-- ($img used to be here but not anymore) +-- img '-- img a <-- $new_parent '-- img <-- $img

In this situation, replacing the $img element with the $new_parent element will obviously not give you what you want (in fact the result would be logically undefined, hence the error message "Can't replace an item with its parent").

On the other hand if you do the  $img->replace_with($new_parent) operation first, it will work just fine and result in this intermediate state:

html <-- $root '-- body +-- h2 +-- a <-- $new_parent ($img used to be here but not anymore) +-- img '-- img img <-- $img

The replaced img element will no longer be part of the document tree, but it continues to exist because we still hold a reference to it in the $img variable. So all that's left to do is to re-add it to the tree using  $new_parent->push_content($img):

html <-- $root '-- body +-- h2 +-- a <-- $new_parent | '-- img <-- $img +-- img '-- img

In reply to Re: HTML Element replace by smls
in thread HTML Element replace by Peamasii

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.