vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
38 lines (37 loc) • 1.55 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __importDefault(require("vanillajs-helpers/isString"));
const findByClass_1 = __importDefault(require("./findByClass"));
const findById_1 = __importDefault(require("./findById"));
const findByTagName_1 = __importDefault(require("./findByTagName"));
const findByQuery_1 = __importDefault(require("./findByQuery"));
function find(elm, selector) {
if ((0, isString_1.default)(elm)) {
[elm, selector] = [document, elm];
}
const query = selector;
const isComplex = [' ', '>', '+', '*', '~', ':', '[', ',']
.some((char) => query.indexOf(char) > -1);
if (!isComplex) {
const firstChar = query[0];
const rest = query.substring(1);
const isId = firstChar === '#';
const isClass = firstChar === '.';
const hasClass = rest.indexOf('.') > -1;
const hasId = rest.indexOf('#') > -1;
if (isId && !hasClass) {
return (0, findById_1.default)(rest);
}
if (isClass && !hasId) {
return (0, findByClass_1.default)(elm, rest.replace(/\./g, ' '));
}
if (!isClass && !isId && !(hasId || hasClass)) {
return (0, findByTagName_1.default)(elm, selector);
}
}
return (0, findByQuery_1.default)(elm, query);
}
exports.default = find;