Skip to content

Instantly share code, notes, and snippets.

@JannesMeyer
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JannesMeyer/7db5fc0dff1fdfe465d6 to your computer and use it in GitHub Desktop.
Save JannesMeyer/7db5fc0dff1fdfe465d6 to your computer and use it in GitHub Desktop.
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule getReactRootElementInContainer
*/
"use strict";
var TEXT_NODE_TYPE = 3;
var COMMENT_NODE_TYPE = 8;
var DOC_NODE_TYPE = 9;
/**
* @param {DOMNode} node DOM node that may be a text node containing only
* whitespace characters or a comment node.
*
* @return {Boolean} true or false whether this node is solely
* comprised of whitespace or a comment.
*/
function isInvisibleNode(node) {
if (node.nodeType === TEXT_NODE_TYPE) {
return !(/[^\t\n\r ]/.test(node.data));
}
if (node.nodeType === COMMENT_NODE_TYPE) {
return true;
}
return false;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component.
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else if (isInvisibleNode(container.firstChild)) {
// Return the second child in hopes that it is an element node
return container.childNodes[1];
} else {
return container.firstChild;
}
}
module.exports = getReactRootElementInContainer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment