UNPKG

phaser

Version:

A fast, free and fun HTML5 Game Framework for Desktop and Mobile web browsers from the team at Phaser Studio Inc.

55 lines (48 loc) 1.78 kB
/** * @author Richard Davey <rich@phaser.io> * @copyright 2013-2026 Phaser Studio Inc. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Adds the given element to the DOM. If a parent is provided, the element is added as a child of the parent element, resolved either by * passing a string ID to `getElementById` or by using the HTMLElement directly. If no parent is given and the element already has an * existing `parentElement`, or if `parent` is explicitly `null`, the element is returned immediately without modification. If no valid * target parent can be resolved, the element is appended to `document.body` as a fallback. * * @function Phaser.DOM.AddToDOM * @since 3.0.0 * * @param {HTMLElement} element - The element to be added to the DOM. Usually a Canvas object. * @param {(string|HTMLElement)} [parent] - The parent in which to add the element. Can be a string which is passed to `getElementById` or an actual DOM object. * * @return {HTMLElement} The element that was passed to this function. */ var AddToDOM = function (element, parent) { var target; if (parent) { if (typeof parent === 'string') { // Hopefully an element ID target = document.getElementById(parent); } else if (typeof parent === 'object' && parent.nodeType === 1) { // Quick test for a HTMLElement target = parent; } } else if (element.parentElement || parent === null) { return element; } // Fallback, covers an invalid ID and a non HTMLElement object if (!target) { target = document.body; } target.appendChild(element); return element; }; module.exports = AddToDOM;