CharacterData: before() method

فهرست فصل‌ها دانلود آرشیوناشر

MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونه‌کد

{{APIRef("DOM")}}

The **before()** method of the {{domxref("CharacterData")}} interface inserts a set of {{domxref("Node")}} objects or strings in the children list of this CharacterData's parent, just before this CharacterData. Strings are inserted as equivalent {{domxref("Text")}} nodes. Nothing happens if {{domxref("Node.parentNode", "parentNode")}} is null.

Syntax

js-nolint
before(param1)
before(param1, param2)
before(param1, param2, /* …, */ paramN)

Parameters

  • param1, …, paramN
  • : A set of {{domxref("Node")}} objects or strings to insert.

Return value

None ({{jsxref("undefined")}}).

Exceptions

  • HierarchyRequestError {{DOMxRef("DOMException")}}
  • : Thrown when the new nodes cannot be inserted at the specified point in the hierarchy, that is if one of the following conditions is met:
  • If the insertion of one of the added node would lead to a cycle, that is if one of them is an ancestor of this {{domxref("CharacterData")}} node.
  • If one of the added node is not a {{domxref("DocumentFragment")}}, a {{domxref("DocumentType")}}, an {{domxref("Element")}}, or a {{domxref("CharacterData")}}.
  • If this {{domxref("CharacterData")}} node is actually a {{domxref("Text")}} node, and its parent is a {{domxref("Document")}}.
  • If the parent of this {{domxref("CharacterData")}} node is a {{domxref("Document")}} and one of the nodes to insert is a {{domxref("DocumentFragment")}} with more than one {{domxref("Element")}} child, or that has a {{domxref("Text")}} child.

Examples

The before() method allows you to insert new nodes before a CharacterData node leaving the current node's data unchanged.

js
const h1TextNode = document.querySelector("h1").firstChild;
h1TextNode.before("h1# ");

h1TextNode.parentElement.childNodes;
// NodeList [#text "h1# ", #text "CharacterData.before()"]

h1TextNode.data;
// "CharacterData.before()"

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}

See also

  • {{domxref("CharacterData.appendData()")}}
  • {{domxref("CharacterData.after()")}}
  • {{domxref("DocumentType.before()")}}
  • {{domxref("Element.before()")}}
  • {{domxref("Element.append()")}}
  • {{domxref("Node.appendChild()")}}
  • {{domxref("Element.insertAdjacentElement()")}}