Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to unwrap a parent node and elevate the children? #202

Open
scott8035 opened this issue Jul 10, 2023 · 0 comments
Open

How to unwrap a parent node and elevate the children? #202

scott8035 opened this issue Jul 10, 2023 · 0 comments

Comments

@scott8035
Copy link

Hi all, I hope it's OK if I ask a question here, I haven't found any other place to ask.

I have the following sample HTML:

<body>
    <div>
        <p>1</p>
        <p>2</p>
        <p>3</p>
    </div>
    <div>
        <p>4</p>
        <p>5</p>
        <p>6</p>
        <div>
            <p>7</p>
            <p>8</p>
            <p>9</p>
        </div>
    </div>
</body>

What I want to do is "unwrap" each <div> by relocating the <p> child nodes to be direct descendants of the div's parent, and deleting the now-empty <div> node. I tried doing it using the code below, but it only works on some nodes; on others, the $tag element has no parent and therefore you can't use insertSiblingBefore(...) without throwing an exception.

Here's some sample code to call the the desired function:

// Remove <div> tags with no attributes
$divTags = $doc->find( 'div' );
foreach ( $divTags as $divTag ) {
    removeElementKeepingChildren( $divTag );
}

...and here's the offending code itself:

function removeElementKeepingChildren( Element $tag ) : void {
    // I'd like to avoid needing this check...but without it, certain $tags cause the exception
    if ( ! $tag->parent() ) {
        return;
    }

    // "Backup" the children
    $children = $tag->children();

    // Remove the children from the node to be removed
    $tag->removeChildren();

    foreach ( $children as $child ) {
        $tag->insertSiblingBefore( $child );
    }

    $tag->remove();
}

There's got to be a better way to do this...suggestions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant