大网数据广告活动
PHP 语言与运行手册

Dom\Element::insertAdjacentHTML · Parses a string as HTML or XML and inserts the result at a given position

· 52CE 我爱测

(No version information available, might only be in Git)

Dom\Element::insertAdjacentHTML

(No version information available, might only be in Git)

Dom\Element::insertAdjacentHTML — Parses a string as HTML or XML and inserts the result at a given position

说明

public function 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.

参数

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.

返回值

没有返回值。

错误/异常

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.

示例

示例 #1 Dom\Element::insertAdjacentHTML() example

<?php

$dom = Dom\HTMLDocument::createFromString(
    '<!DOCTYPE html><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";

以上示例会输出:

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

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。