Replace first <p> tag with HTML DOM

Q: In accordance with the task, I need to replace the tag <p>only for the first entry with h4, using HTML DOM.

I am trying to use this question but cannot succeed

My code

HTML

<div class="productabcont">
    <div class="protabtop">
        <div class="protabtopright">
            <p>Combed compact yarn</p> <!-- This i want to replace with <h4> tag. -->
            <p>Description line 1</p>
            <p>Description line 2</p>
        </div>
    </div>          
</div>

Php

<?php    
    $dom = new DOMDocument();
    $dom->loadHTML($myHTML);
    $dom->getElementsByTagName('p')[0]->outertext = '<h4>'.$value.'</h4>';
    $dom->saveHTML();
?>

Required conclusion

<div class="productabcont">
    <div class="protabtop">
        <div class="protabtopright">
            <h4>Combed compact yarn</h4> <!-- This is replaced with <p> tag. -->
            <p>Description line 1</p>
            <p>Description line 2</p>
        </div>
    </div>          
</div>

Thanks in advance.

+4
source share
2 answers

When using objects, DOM*no outerHTML. But you can use all available tools.

For instance:

<?php

$html = <<<HTML
<div class="productabcont">
    <div class="protabtop">
        <div class="protabtopright">
            <p>Combed compact yarn</p> <!-- This i want to replace with <h4> tag. -->
            <p>Description line 1</p>
            <p>Description line 2</p>
        </div>
    </div>          
</div>
HTML;

$value = 'some headline';

$dom = new DOMDocument();
$dom->loadHTML($html);

$q = new DOMXPath($dom);

// find first p tag
foreach ($q->query('//p[1]') as $p) {
    // replace it with newly created element
    $p->parentNode->replaceChild($dom->createElement('h4', $value), $p);
}

echo $dom->saveHTML();

Of course, you do not need to use xpath for such a simple example, but if later you need to specify more clearly which node to replace, it will easily expand.

: https://3v4l.org/4Hj1e

+1

, DOM jQuery.

: jsfiddle

var firstText = $(".protabtopright p:first").text();
$(".protabtopright p:first").replaceWith("<h4>" + firstText + "</h4>");
-1

Source: https://habr.com/ru/post/1681328/


All Articles