From 95903fe7f4125c3570e042dce085f28458a4c4d1 Mon Sep 17 00:00:00 2001 From: Thomas Erbe Date: Fri, 27 Jul 2018 23:05:46 +0100 Subject: [PATCH] Add a `findElement` helper to normalise the method of finding an element within a plugin --- src/core.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/core.js b/src/core.js index c36b848..8e2a17b 100644 --- a/src/core.js +++ b/src/core.js @@ -109,6 +109,30 @@ const Bulma = { }); return elem; + }, + + /** + * Helper method to normalise a plugin finding an element. + * @param {string} query + * @param {HTMLElement|null} context + * @param {boolean} nullable + * @returns {null|HTMLElement} + * @throws {TypeError} + */ + findElement(query, context = document, nullable = false) { + if(!query && !nullable) { + throw new TypeError('First argument to `findElement` required. Null given.'); + } + + if(!query) { + return null; + } + + if(query.toString() === '[object HTMLElement]') { + return query; + } + + return context.querySelector(query); } };