medialize/ally.js

View on GitHub
src/util/context-to-element.js

Summary

Maintainability
A
25 mins
Test Coverage

import nodeArray from '../util/node-array';

export default function({
  context,
  label = 'context-to-element',
  resolveDocument,
  defaultToDocument,
}) {
  let element = nodeArray(context)[0];

  if (resolveDocument && element && element.nodeType === Node.DOCUMENT_NODE) {
    element = element.documentElement;
  }

  if (!element && defaultToDocument) {
    return document.documentElement;
  }

  if (!element) {
    throw new TypeError(label + ' requires valid options.context');
  }

  if (element.nodeType !== Node.ELEMENT_NODE && element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
    throw new TypeError(label + ' requires options.context to be an Element');
  }

  return element;
}