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.