@exadel/esl
Version:
Exadel Smart Library (ESL) is the lightweight custom elements library that provide a set of super-flexible components
48 lines (47 loc) • 1.76 kB
JavaScript
import { isObject, isPlainObject } from '../misc/object/types';
/** Checks that passed value is an DOM Element Node */
export const isElement = (el) => {
return isObject(el) && el.nodeType === 1 && !isPlainObject(el);
};
/**
* Get the Element that is the root element of the document.
* @param element - element for which to get the document element
* */
export const getDocument = (element = window) => {
return (element instanceof Window ? element.document : element.ownerDocument).documentElement;
};
/**
* Get the name of node.
* @param element - element for which to get the name
*/
export const getNodeName = (element) => {
return element && !(element instanceof Window) ? (element.nodeName).toLowerCase() : '';
};
/**
* Get the parent of the specified element in the DOM tree.
* @param element - element for which to get the parent
*/
export const getParentNode = (element) => {
if (getNodeName(element) === 'html')
return element;
return (window.ShadowRoot
? element instanceof ShadowRoot
? element.host
: element.assignedSlot || element.parentNode
: element.parentNode) || getDocument(element);
};
/**
* Converts HTML string or other input to a DOM Element.
* @param input - HTML string to parse, Element to return as-is, or array of elements to get first from
* @returns DOM Element, or undefined if no element can be resolved from the input
*/
export const htmlToElement = (input) => {
// Element - return as-is
if (isElement(input))
return input;
// Array of elements - return first
if (Array.isArray(input))
return input[0];
// String - parse HTML
return (new DOMParser()).parseFromString(input, 'text/html').body.children[0];
};