php8.5
Home/ Manual/ dom / element/ Dom\Element::insertAdjacentHTML

Dom\Element::insertAdjacentHTML

PHP function Edit on GitHub ✎

Parses a string as HTML or XML and inserts the result at a given position

Description

Dom\Element::insertAdjacentHTML(Dom\AdjacentPosition $where, string $string): void

Parses string as a fragment and inserts the resulting nodes at the position given by where, relative to this element. The fragment is parsed as HTML in an HTML document, and as XML in an XML document.

Parameters

where

A Dom\AdjacentPosition case that specifies where the nodes are inserted relative to this element.

string

The HTML or XML markup to parse. In an XML document it must be a well-formed XML fragment.

Return Values

Void

Errors/Exceptions

Throws a DOMException with code Dom\NO_MODIFICATION_ALLOWED_ERR if where is Dom\AdjacentPosition::BeforeBegin or Dom\AdjacentPosition::AfterEnd and this element has no parent, or its parent is the document.

Throws a DOMException with code Dom\SYNTAX_ERR if this element is in an XML document and string is not a well-formed XML fragment.

Examples

Dom\Element::insertAdjacentHTML example

php
<?php

$dom = Dom\HTMLDocument::createFromString(
    '<body><ul id="list"><li>Two</li></ul></body>',
    LIBXML_NOERROR
);

$list = $dom->getElementById('list');

$list->firstElementChild->insertAdjacentHTML(
    Dom\AdjacentPosition::BeforeBegin,
    '<li>One</li>'
);
$list->insertAdjacentHTML(
    Dom\AdjacentPosition::BeforeEnd,
    '<li>Three</li><li><b>Four</b></li>'
);

echo $list->outerHTML, "\n";

The above example will output:

output
<ul id="list"><li>One</li><li>Two</li><li>Three</li><li><b>Four</b></li></ul>

See Also

Source: reference/dom/dom/element/insertadjacenthtml.xml · from the official PHP manual (php/doc-en)