Keep It Simple, Stupid | |
PerlMonks |
Re: HTML Element replaceby smls (Friar) |
on May 17, 2014 at 10:07 UTC ( [id://1086427]=note: print w/replies, xml ) | Need Help?? |
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:
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:
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):
In Section
Seekers of Perl Wisdom
|
|