Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. Web API
  3. Element
  4. Element:prepend() 方法

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

Element:prepend() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2018年4月.

Element.prepend() 方法将在当前元素的第一个子节点之前插入一组Node 对象或字符串。字符串将以等效的Text 节点插入。

语法

js
prepend(param1)prepend(param1, param2)prepend(param1, param2, /* …, */ paramN)

参数

param1、……、paramN

一组要插入的Node 对象或字符串。

返回值

无(undefined)。

异常

HierarchyRequestErrorDOMException

当节点无法插入到指定的层级位置时抛出。

示例

在元素前插入

js
let div = document.createElement("div");let p = document.createElement("p");let span = document.createElement("span");div.append(p);div.prepend(span);console.log(div.childNodes); // NodeList [ <span>, <p> ]

在文本前插入

js
let div = document.createElement("div");div.append("一些文本");div.prepend("标题:");console.log(div.textContent); // “标题:一些文本”

在元素前插入元素和文本

js
let div = document.createElement("div");let p = document.createElement("p");div.prepend("一些文本", p);console.log(div.childNodes); // NodeList [ #text "一些文本", <p> ]

prepend 方法是不可绑定作用域的

prepend() 方法无法绑定到with 语句中的作用域。有关更多信息,请参阅Symbol.unscopables

js
let div = document.createElement("div");with (div) {  prepend("foo");}// ReferenceError: prepend is not defined

规范

Specification
DOM
# ref-for-dom-parentnode-prepend①

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp