Clément Andraud
Clément Andraud

Reputation: 9269

How can i insert something just before the close tag of an element?

I need to correct something in a lot of html documents.

So, i have a structure like this in my body (simplified) :

<body>
    <div id="inter">
        <!-- some content -->
    </div>
</body>

I need to insert something just before the close tag of my div id="inter". I have to make use of PHP and DOMDocument I guess.

So I get something like:

<body>
    <div id="inter">
        <!-- some content -->
        @insert something here
    </div>
</body>

In my <div id="inter">, I can have a lot of content, like other div, image, span, etc.

Do you know how can I do that?

Upvotes: 0

Views: 1459

Answers (2)

PeeHaa
PeeHaa

Reputation: 72672

You can do this with createElement() and appendChild():

$newElem = $doc->createElement('p', 'New element');
$doc->getElementById('inter')->appendChild($newElem);

Demo: http://codepad.viper-7.com/GMGjkd

If you want to add a comment you can simply use the following:

$newComment = $doc->createComment('New comment');
$doc->getElementById('inter')->appendChild($newComment);

Demo: http://codepad.viper-7.com/QMuDMt

Upvotes: 3

Quentin
Quentin

Reputation: 943223

appendChild will add a node to the end of another node.

You can create a comment node with DOMComment

Upvotes: 0

Related Questions