form-cheatsheet/src/doc.js

66 lines
1.5 KiB
JavaScript

/**
* Simple DOM helper methods
*/
class Doc {
/**
* Get the list of script elements currently loaded
*
* @return {Element[]}
*/
static scripts() {
return Array.from(document.scripts);
}
/**
* Search for an HTML element by css selector
*
* @param {string} sel - The css selector
* @param {Element} [context] - An optional parent element to search from
* @return {Element}
*/
static qs(sel, context = document.documentElement) {
if (document.OLD_IE) {
return document.documentElement.querySelector.call(context, sel);
}
return context.querySelector(sel);
}
/**
* Get an array of HTML elements by css selector
*
* @param {string} sel - The css selector
* @param {Element} [context] - An optional parent element to search from
* @return {Element[]}
*/
static qsa(sel, context = document.documentElement) {
if (document.OLD_IE) {
return Array.from(document.documentElement.querySelectorAll.call(context, sel));
}
return Array.from(context.querySelectorAll(sel));
}
/**
* Get an HTML element by its id attribute
*
* @param {string} id
* @return {Element}
*/
static getById(id) {
return document.getElementById(id);
}
/**
* Get an array of HTML elements by their tag (element) name
*
* @param {string} tagName
* @param {Element} [context] - An optional parent element to search from
* @return {Element[]}
*/
static getByTag(tagName, context = document.documentElement) {
return Array.from(context.getElementsByTagName(tagName));
}
}
export default Doc;