wasinger / htmlpagedom

jQuery-inspired DOM manipulation extension for Symfony's Crawler
MIT License
346 stars 50 forks source link

replaceWith / before / after etc. are not working?! #43

Open BernhardBaumrock opened 1 year ago

BernhardBaumrock commented 1 year ago

Thx for the great library, really helpful! I'm using it to create docs for my open source modules where I'm parsing markdown to html and then adding some customisations.

This has worked very well so far, but now I'm hitting some roadblocks:

$crawler
  ->filter("p")
  ->each(function (HtmlPageCrawler $node) {
    // this works
    $node->addClass("foobar");

    // this does not work
    $node->replaceWith("<div>foobar</div>");

    // this works
    $node->append("<div>test</div>");
  });

append() works, but I'm actually trying to add some label markup like <div>my label</div> after every img and on image tags append() does obviously not work which is why I'm trying to use after() which unfortunately does also not work at all :(

Am I missing something?

BernhardBaumrock commented 1 year ago

Ok I just found the issue myself!

If you have this code:

<h1>some html</h1>
<p>foo bar</p>
<img src=/foo/bar.png>

And you try this:

$crawler
      ->filter("img")
      ->each(function (HtmlPageCrawler $node) {
          $node->after("<div class='uk-text-center'>image label</div>");
      });

It will not work because you don't have a parent node and therefore the parser can't add the new node after the image tag.

When wrapping everything in one single root div everything works as expected.

<div>
    <h1>some html</h1>
    <p>foo bar</p>
    <img src=/foo/bar.png>
</div>

Not sure if that is a bug and it should automatically wrap "flat" html code in a root element to make sure that after() before() etc. are working? Or at least it would be nice to mention that in the docs :)

Thx again for the brilliant library!