dongyuan7110 2019-04-05 03:31
浏览 293

添加元素作为特定div中的第一个子元素 - php

I want to add the element h3 in div element of class 'jumbotron'. And, this h3 has to be the first child of div. The problem is the div can have various elements and I cannot use the insertBefore (DOMNode).

I'm using php language.

First, I have this code:

<div class="jumbotron" name="div_jbt" id="div1">
     <p>text etc...</p>
     <img src="../img.jpg">
</div>

I want to add the element h3 as first child of this div:

<div class="jumbotron" name="div_jbt" id="div1">
     <h3>Title</h3>
     <p>text etc...</p>
     <img src="../img.jpg">
</div>

Or, in another case, I can have this code:

<div class="jumbotron" name="div_jbt" id="div1">
     <div>test</div>
     <img src="../img.jpg">
     <p>text etc...</p>
</div>

Similarly, I want to add the element h3 as first child of this div:

<div class="jumbotron" name="div_jbt" id="div1">
     <h3>Title</h3>
     <div>test</div>
     <img src="../img.jpg">
     <p>text etc...</p>
</div>

PHP code:

$doc = new DOMDocument();
$doc->loadHTML($html);
// find the 1º div
$div = $doc->getElementsByTagName("div")->item(0);
// create new h3 tag
$h3 = $doc->createElement("h3", "Title test"); 
// insert created element after 1º div
$div->parentNode->insertBefore($h3, $div); 
$html = $doc->saveHTML();

So, I want to add h3 element as first child into the div class jumbotron in any case.

EDIT: I did this:

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

$h3 = $dom->createElement("h3", "Title test"); 

$dom->insertBefore($h3, $dom->firstChild);

$body = $dom->saveHTML();
$string_body .= $body;

But it didn't work.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Vue3 大型图片数据拖动排序
    • ¥15 划分vlan后不通了
    • ¥15 GDI处理通道视频时总是带有白色锯齿
    • ¥20 用雷电模拟器安装百达屋apk一直闪退
    • ¥15 算能科技20240506咨询(拒绝大模型回答)
    • ¥15 自适应 AR 模型 参数估计Matlab程序
    • ¥100 角动量包络面如何用MATLAB绘制
    • ¥15 merge函数占用内存过大
    • ¥15 使用EMD去噪处理RML2016数据集时候的原理
    • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大