Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: HTML Element replace

by smls (Friar)
on May 17, 2014 at 10:07 UTC ( [id://1086427]=note: print w/replies, xml ) Need Help??


in reply to HTML Element replace

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

Replies are listed 'Best First'.
Re^2: HTML Element replace
by Peamasii (Sexton) on May 17, 2014 at 11:58 UTC
    Great, I understand it now. thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1086427]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-19 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found