# addClass
addClass(elm: any, classNames: string | string[]): elm
Adds one or multiple class names to a DOM element
@returns : The given elm
Examples
addClass(MyNode, 'active') // --> <div class="active" />
addClass(MyNode, ['active', 'open']) // --> <div class="active open" />
# append
append(elm: Element, insertElm: any): Element | null
Append DOM element or plain HTML to the end of a given DOM element
@returns : The inserted child element
Examples
append(MyNode, NodeToAppend)
append(MyNode, '<span>appended</span>')
append(MyNode, '.my-appended-element')
# attr
attr(elm: Element, attrName: string, value?: null | string | number | boolean): string | null
Get/set the value of an attribute on a given DOM element
@returns : Data found in the attribute (the old value if {value} is defined)
Examples
// Get the value of an attribute
attr(document.documentElement, 'lang'); // --> eg. 'en-US'
// Set the value of an attribute
attr(document.documentElement, 'lang', 'da-DK'); // --> <html lang="da-DK">
// Set a boolean value
attr(MyInput, readonly, true); // --> <input readonly />
attr(MyInput, readonly, false); // --> <input />
# boxModel
boxModel(elm: Element): BoxModelMapping
Parses the box model numbers of an given Element (margin, padding and border widths)
@returns : The mapping of the box model
Examples
boxModel(someDiv);
Types
type BoxModelMapping = {
border: BoxModelSectionMapping
margin: BoxModelSectionMapping
padding: BoxModelSectionMapping
};
type BoxModelSectionMapping = {
bottom: number
left: number
right: number
top: number
};
# children
children(elm: ParentNode): Element[]
Find the children of a given DOM element and return it as an Array
@returns : List of found child DOM elements
Examples
children(someDiv);
# classNameString
classNameString(args: (Option | Option[])[]): string
Create a string of names that will be used as class names for a given element.
@returns : The list of class names (eg. "my-elm open active")
Examples
classNames('my-elm', 'open', 'active') // --> "my-elm open active"
classNames(['my-elm', 'open', 'active']) // --> "my-elm open active"
classNames('my-elm', ['open', 'active']) // --> "my-elm open active"
classNames('my-elm', { open: true, active: true }) // --> "my-elm open active"
Types
type Option = string | Record<string, boolean | undefined>;
# contentBoxSize
contentBoxSize(elm: any): {
height: number
width: number
}
Find the size of a DOM element, document or window excluding borders, margins and padding
(Getting the size of the viewport if document
or window
is given)
@returns : Object describing width and height of the element
Examples
// <div style="width: 200px; height: 300px; margin: 10px; border: 2px solid;" />
contentBoxSize(div) // --> { width: 200, height: 300 }
contentBoxSize(window) // --> [size of the viewport]
contentBoxSize(document) // --> [size of the viewport]
# contentSize
contentSize(elm: any): {
height: number
width: number
}
Find the size of the content (scrollable area minus padding) of a DOM element, document or window
(Getting the size of the viewport if document
or window
is given)
@returns : Object describing width and height of the element
Examples
// <div style="width: 200px; height: 200px; margin: 10px; border: 2px solid; overflow: scroll">
// <div style="height: 400px; width: 400px" />
// </div>
contentSize(div) // --> { width: 400, height: 400 }
contentSize(window) // --> [size of the viewport]
contentSize(document) // --> [size of the viewport]
# copyEvent
copyEvent<T extends Event>(event: T, currentTarget?: EventTarget): T
Copies a given event and optionally changes the currentTarget
@returns : The copied event
Examples
copyEvent(SomeEvent, MyNewCurrentTargetElement)
# createElement
createElement(selector?: string): Element
Creates an element from a given CSS selector (restricted to only one element)
@returns : The created element
Examples
// Create a div
create(); // --> <div />
// Create an element
create('img'); // --> <img />
// Create an element from a selector
create('#MyElement.active'); // --> <div id="MyElement" class="active" />
# css
css(elm: HTMLElement): CSSStyleDeclaration
Get the computed styling of a DOM element.
@returns : All styling on the element
Examples
css(MyElm) // --> All computed styles of MyElm
Types
type CSSStyleProperties = Record<string, string | number | null | undefined>;
css(elm: HTMLElement, property: string): string | number | null
Gets a given inline style property on a DOM element.
Return values that are pure numbers or pixel values will be converted to pure number first
@returns : All styling on the element or the value of the given style property
Examples
css(MyElm, 'font-size') // --> 30
css(MyElm, 'borderSize') // --> '1px'
Types
type CSSStyleProperties = Record<string, string | number | null | undefined>;
css(elm: HTMLElement, styles: CSSStyleProperties): CSSStyleDeclaration
Set multiple inline styling properties on a DOM element.
Notes on values:
null
as value, removes the given property!important
in the value will be parsed and set correctly (eg. font-size: 15px !important)
@returns : All styling on the element
Examples
css(MyElm, { fontSize: 30, 'font-weight': 'bold !important' }) // --> All computed styles of MyElm
Types
type CSSStyleProperties = Record<string, string | number | null | undefined>;
css(elm: HTMLElement, property: string, value: null | string | number): CSSStyleDeclaration
Set a given inline style property on a DOM element.
Notes on values:
null
removes the given property!important
added to the value, it will be parsed and set correctly
@returns : All styling on the element or the value of the given style property
Examples
css(MyElm, 'fontSize', 30) // --> All computed styles of MyElm
Types
type CSSStyleProperties = Record<string, string | number | null | undefined>;
# domReady
domReady(handler: () => void): void
Execute a given function once the document has finished loading
Examples
domReady((e: Event) => { alert('DOM Ready') });
docComplete(): boolean
returns whether document ready state indicates that the document is ready to be manipulated
# elementData
elementData(elm: Node, key?: string, data?: unknown): unknown
Inspired by jQuery's data method that stores data in memory associated with a given element.
If no data is given, the stored data for the given key is returned. If no key is given either
the entire data object will be returned.
@returns : The entire cache or the data for the given key
Examples
elementData(MyElm, 'entry', { count: 10 }) // --> { count: 10 }
elementData(MyElm, 'entry') // --> <What ever was stored under "entry">
elementData(MyElm) // --> everything was stored for the given element
resetCache(): void
Resets ALL local data cache
# elmIndex
elmIndex(elm: Element): number
Find the index of a DOM element amongst its siblings
@returns : The index of elm
Examples
elmIndex(someDiv); // --> 3
# ensureHTML
ensureHTML(htmlOrSelector: string): string
Parses a string to see if it is already HTML otherwise it assumes
is a selector and parses it to HTML
@returns : The HTML string
Examples
// String is already HTML so it is returned as is
ensureHTML('<div />');
// String is a selector, to is is parsed before it is returned
ensureHTML('.my-div'); // --> <div class="my-div" />
# find
find<T extends HTMLElement>(selector: string): T | T[] | null
Find elements by a given selector. The selector will be lightly analyzed to determine
the appropriate findByXX
function. This should be faster than just running querySelector(All)
to find elements.
@returns : List of found DOM elements
Examples
find('#my-id') // Uses getElementById()
find('.my-class') // Uses getElementsByClassName()
find('div') // Uses getElementsByTagName()
find('#my-id.my-class') // Uses querySelectorAll()
find('#my-id > .my-class + p') // Uses querySelectorAll()
find<T extends HTMLElement>(elm: Maybe<any>, selector: string): T | T[] | null
Find elements by a given selector from a given element. The selector will be lightly analyzed to determine
the appropriate findByXX
function. This should be faster than just running querySelector(All)
to find elements.
@returns : List of found DOM elements
Examples
find(myElm, '#my-id') // Uses myElm.querySelectorAll()
find(myElm, '.my-class') // Uses myElm.getElementsByClassName()
find(myElm, 'div') // Uses myElm.getElementsByTagName()
find(myElm, '#my-id.my-class') // Uses myElm.querySelectorAll()
find(myElm, '#my-id > .my-class + p') // Uses myElm.querySelectorAll()
# findByClass
findByClass<T extends HTMLElement>(classNames: string | string[]): T[]
Finds DOM elements with a given class name.
Separate multiple selectors by comma. Separate multiple class names by space.
@returns : List of found DOM elements
Examples
findByClass('my-id') // --> all ".my-elm" elements
findByClass('my-id, my-other-elm') // --> all ".my-elm" and ".my-other-elm" elements
findByClass('my-id my-other-elm') // --> all ".my-elm.my-other-elm" elements
findByClass<T extends HTMLElement>(elm: Maybe<any>, classNames: string | string[]): T[]
Finds DOM elements with a given class name from a given element.
Separate multiple selectors by comma. Separate multiple class names by space.
@returns : List of found DOM elements
Examples
findByClass(myElm, 'my-id') // --> all ".my-elm" elements as descendant of myElm
findByClass(myElm, 'my-id, my-other-elm') // --> all ".my-elm" and ".my-other-elm" elements as descendant of myElm
findByClass(myElm, 'my-id my-other-elm') // --> all ".my-elm.my-other-elm" elements as descendant of myElm
# findById
findById<T extends HTMLElement>(id: string): T | null
Find a DOM element with the given ID
@returns : The found element
Examples
findById('my-id') // --> "#my-id" element
findById('non-existing') // --> null
findById<T extends HTMLElement>(ids: string[]): T[]
Find a DOM elements from a list of IDs
@returns : The found elements
Examples
findById(['my-id', 'my-other-id']) // --> "#my-id" and "#my-other-elm" elements
findById(['non-existing', 'non-existing-2']) // --> []
# findByName
findByName<T extends HTMLElement>(names: string | string[]): T[]
Find DOM elements with the given name
@returns : List of found DOM elements
Examples
findByName('my-element-name') // --> all "[name=my-element-name]" elements
findByName(['my-element-name', 'my-second-name']) // --> all "[name=my-element-name]" and "[name=my-second-name]" elements
# findByQuery
findByQuery<T extends HTMLElement>(elm: Maybe<any>, queries: string | string[]): T[]
Find all elements matching a given CSS selector from a given element
@returns : List of found DOM elements
Examples
findByQuery(MyElm, 'span.my-class') // --> All "span.my-class" elements that are descendants of MyElm
Types
type OneArgs = [elm: undefined, query: string];
findByQuery<T extends HTMLElement>(queries: string | string[]): T[]
Find all elements matching a given CSS selector
@returns : List of found DOM elements
Examples
findByQuery('span.my-class') // --> All "span.my-class" elements that are descendants of document
Types
type OneArgs = [elm: undefined, query: string];
findOneByQuery<T extends HTMLElement>(elm: Maybe<any>, query: string): T | null
Find first elements matching a given CSS selector from a given element
@returns : List of found DOM elements
Examples
findOneByQuery(MyElm, 'span.my-class') // --> First "span.my-class" elements that are descendants of MyElm
findOneByQuery<T extends HTMLElement>(query: string): T | null
Find first elements matching a given CSS selector
@returns : List of found DOM elements
Examples
findOneByQuery('span.my-class') // --> First "span.my-class" elements that are descendants of document
# findByTagName
findByTagName<T extends HTMLElement>(tagNames: string | string[]): T[]
Find elements by given tag name
@returns : List of found DOM elements
Examples
findByTagName('div') // --> All <div> elements
findByTagName<T extends HTMLElement>(elm: Maybe<any>, tagNames: string | string[]): T[]
Find elements by given tag name
@returns : List of found DOM elements
Examples
findByTagName(MyElm, 'div') // --> All <div> elements that are descendants of MyElm
# getCurrentDocument
getCurrentDocument(node: any): Document | null
Determines the relevant owner document
object from a give node
@returns : The owner document (if can be determined)
Examples
getCurrentDocument(document) // --> `document` directly
getCurrentDocument(window) // --> `window.document`
getCurrentDocument(myNode) // --> The `document` in which myNode resides
# getCurrentWindow
getCurrentWindow(node: any): GeneralWindow | null
Determines the relevant owner window
object from a give node
@returns : The owner window (if can be determined)
Examples
getCurrentWindow(document) // --> `window` the document belongs to
getCurrentWindow(window) // --> `window` directly
getCurrentWindow(myNode) // --> The `window` in which myNode resides
# hasClass
hasClass(elm: any, classNames: string | string[], any?: boolean): boolean
Does all (or any) of the listed class names exist in the DOM elements list of class names
@returns : All/any class names listed were found in the elements list of class names
Examples
hasClass(myElm, 'open') // --> true if myElm has the "open" class name
hasClass(myElm, ['open', 'shown']) // --> true if myElm has some or all given class names
hasClass(myElm, ['open', 'shown'], true) // --> true if myElm has all given class names
hasAllClass(elm: Element, classNames: string | string[]): boolean
Does all of the listed class names exist in the DOM elements list of class names
@returns : All of the class names listed were found in the elements list of class names
Examples
hasAllClassNames(myElm, 'open') // --> true if myElm has the "open" class name
hasAllClassNames(myElm, ['open', 'shown']) // --> true if myElm has all given class names
hasAnyClass(elm: Element, classNames: string | string[]): boolean
Does any of the listed class names exist in the DOM elements list of class names
@returns : At least one of the class names listed were found in the elements list of class names
Examples
hasAnyClassName(myElm, 'open') // --> true if myElm has the "open" class name
hasAnyClassName(myElm, ['open', 'shown']) // --> true if myElm has at least one of the given class names
# inDOM
inDOM(elm: Node): boolean
Is the given DOM node inserted into the DOM
@returns : Is it a DOM node in the DOM or not
Examples
inDOM(document.getElementById('my-elm')) // --> true
inDOM(document.createElement('div')) // --> false
# innerSize
innerSize(elm: any): {
height: number
width: number
}
Find the size of a DOM element, document or window excluding borders, margins and scrollbars.
Getting the size of the viewport if document
or window
is given.
@returns : Object describing width and height of the element
Examples
// <div style="width: 200px; height: 300px; margin: 15px; padding: 10px; border-width: 2px;" />
innerSize(div) // --> { width: 220, height: 320 }
innerSize(window) // --> [size of the viewport]
innerSize(document) // --> [size of the viewport]
# innerXML
innerXML(elm: Element): string
Gets the inner XML structure as a string from a XML/HTML element
(like innerHTML but also for XML elements - eg. in SVG)
@returns : The inner XML structure
Examples
innerXML(<div><span>my text</span></div>); // --> '<span>my text</span>'
innerXML(<svg><g><path /></g></svg>); // --> '<g><path /></g>'
# insertAfter
insertAfter(elm: Element, insertElm: any): Element | null
Inserts DOM element or plain HTML after a given DOM element
(not possible for detached elements or the element)
@returns : The inserted element
Examples
insertAfter(document.documentElement, myInsertElm) // --> null (not possible)
insertAfter(document.createElement('div'), myInsertElm) // --> null (not possible)
insertAfter(myElm, myInsertElm) // --> myInsertElement
insertAfter(myElm, '<div />') // --> <div />
insertAfter(myElm, '.inserted-element') // --> <div class="inserted-element" />
# insertBefore
insertBefore(elm: Element, insertElm: any): Element | null
Inserts DOM element or plain HTML before a given DOM element
(not possible for detached elements or the element)
@returns : The inserted element
Examples
insertBefore(document.documentElement, myInsertElm) // --> null (not possible)
insertBefore(document.createElement('div'), myInsertElm) // --> null (not possible)
insertBefore(myElm, myInsertElm) // --> myInsertElement
insertBefore(myElm, '<div />') // --> <div />
insertBefore(myElm, '.inserted-element') // --> <div class="inserted-element" />
# inView
inView(elm: HTMLElement, threshold?: number): PositionIndicator
Determines whether the element is in the area of the viewport or not.
@returns : An object with indications of where the element is compared to the viewport area
Examples
// Element inside viewport
const { inside } = inView(myElement); // --> inside === true
// Element outside viewport
const { inside, below } = inView(myElement); // --> inside === false; below === true
// With a threshold
const { inside } = inView(myElement, 30); // --> inside === true
Types
type PositionIndicator = {
// Above the viewport area?
above: boolean
// Below the viewport area?
below: boolean
// Inside the viewport area?
inside: boolean
// To the left of the viewport area?
left: boolean
// To the right of the viewport area?
right: boolean
};
# invisible
invisible(elm: HTMLElement): boolean
Test if a given DOM element is invisible.
Itself or a parent is:
- hidden
- No width or no height
- opacity: 0
@returns : Is the element invisible
Examples
invisible(document.body) // --> false
invisible(MyNormalElement) // --> false
invisible(myZeroHeightElement) // --> true
invisible(myZeroWidthElement) // --> true
invisible(myNoDisplayElement) // --> true
invisible(myNoVisibilityElement) // --> true
# isBlob
isBlob(obj: unknown): boolean (obj is Blob)
Is the given object a Blob object
@returns : Is it a Blob object or not
Examples
isBlob(new Blob()) // --> true
isBlob('blob') // --> false
# isDocument
isDocument(obj: unknown): boolean (obj is Document)
Is the given object a DOM document node
@returns : Is it a DOM document node or not
Examples
isDocument(window.document) // --> true
isDocument(window) // --> false
isDocument(document.body) // --> false
# isDOMChildNode
isDOMChildNode(node: unknown): boolean (node is ChildNodeWithParent)
Is the given object a DOM node child of a DOM element
@returns : Is it a DOM child node or not
Examples
isDOMChildNode(document.body) // --> true
isDOMChildNode(document.getElementById('my-elm')) // --> true
isDOMChildNode(createDetachedDocument().body) // --> true
isDOMChildNode(document.documentElement) // --> false
# isDOMContainer
isDOMContainer(obj: unknown): boolean
Is the given object a DOM node that can contain child DOM nodes
@returns : Is it a DOM container or not
Examples
isDOMContainer(document.documentElement) // --> true
isDOMContainer(document.body) // --> true
isDOMContainer(document.getElementById('my-elm')) // --> true
isDOMContainer(document.createDocumentFragment()) // --> true
isDOMContainer(document) // --> false
isDOMContainer(document.createTextNode('')) // --> false
# isDOMElement
isDOMElement(obj: unknown): boolean (obj is Element)
Is the given object a DOM element node and optionally of a given type
@returns : Is it a DOM element node or not and optionally of the right type
Examples
isDOMElement(document.createElement('p')) // --> true
isDOMElement(document.documentElement) // --> true
isDOMElement(document.body) // --> true
isDOMElement(window) // --> false
isDOMElement(document.createTextNode('')) // --> false
# isDOMFragment
isDOMFragment(obj: unknown): boolean (obj is DocumentFragment)
Is the given object a Document Fragment
@returns : Is it a Document Fragment or not
Examples
isDOMFragment(document.createDocumentFragment()) // --> true
isDOMFragment(document.createElement('p')) // --> false
isDOMFragment(document) // --> false
isDOMFragment(window) // --> false
# isDOMNode
isDOMNode(node: unknown): boolean (node is Node)
Is the given object a DOM Node
@returns : Is it a DOM node or not
Examples
isDOMNode(document.documentElement) // --> true
isDOMNode(document.createTextNode('')) // --> true
isDOMNode(document.createComment('')) // --> true
isDOMNode(window) // --> false
# isDOMRoot
isDOMRoot(node: unknown): boolean (node is HTMLElement)
Is the given object root node of the DOM (eg <html>
for HTML documents og <svg>
for SVG documents)
@returns : Is it the root node of the DOM or not
Examples
isDOMRoot(document.documentElement) // --> true
isDOMRoot(document.body) // --> false
isDOMRoot(document) // --> false
isDOMRoot(window) // --> false
# isEventTarget
isEventTarget(obj: unknown): boolean (obj is EventTarget)
Is the given object a viable event target (implements the addEventListener function)
@returns : Is it an Event Target or not
Examples
isEventTarget(window) // --> true
isEventTarget(document) // --> true
isEventTarget(document.documentElement) // --> true
isEventTarget(document.body) // --> true
isEventTarget(new XMLHttpRequest()) // --> true
isEventTarget({}) // --> false
# isHTMLChildElement
isHTMLChildElement(node: unknown): boolean (node is HTMLChildElement)
Is the given object a DOM node child of a DOM element
@returns : Is it a child HTMLElement or not
Examples
isHTMLChildElement(document.body) // --> true
isHTMLChildElement(document.getElementById('my-elm')) // --> true
isHTMLChildElement(createDetachedDocument().body) // --> true
isHTMLChildElement(document.documentElement) // --> false
# isHTMLElement
isHTMLElement(obj: unknown): boolean (obj is HTMLElement)
Is the given object a HTMLElement node
@returns : Is it a HTML element node
Examples
isHTMLElement(document.createElement('p')) // --> true
isHTMLElement(document.documentElement) // --> true
isHTMLElement(document.body) // --> true
isHTMLElement(window) // --> false
isHTMLElement(document.createTextNode('')) // --> false
# isWindow
isWindow(obj: unknown): boolean (obj is GeneralWindow)
Is the given object a Window object (eg. window or IFrame.contentWindow)
@returns : Is it a Window object or not
Examples
isWindow(window) // --> true
isWindow(document) // --> false
isWindow(document.body) // --> false
# marginBoxSize
marginBoxSize(elm: any): {
height: number
width: number
}
Find the size of a DOM element, document or window including margins and borders
(Getting the size of the viewport if document
or window
is given)
@returns : Object describing width and height of the element
Examples
// <div style="width: 200px; height: 300px; margin: 15px; padding: 10px; border-width: 2px;" />
marginBoxSize(div) // --> { width: 254, height: 354 }
marginBoxSize(window) // --> [size of the viewport]
marginBoxSize(document) // --> [size of the viewport]
# nextSiblings
nextSiblings(elm: Element): Element[]
Get all sibling elements after a given DOM element in the structure
@returns : Collection of sibling elements
Examples
nextSiblings(someElement);
# off
off<E extends EventName>(elm: EventTarget, eventNames: E | E[], handler: EventHandler, options?: any): elm
Bind an event handler for one or more event names on a given DOM element.
@returns : elm
Examples
off(MyElm, 'click', () => {})
off(MyElm, 'click', () => {}, { passive: true })
off(MyElm, ['mouseenter', 'touchstart'], () => {})
off<E extends EventName>(eventNames: E | E[], handler: EventHandler, options?: any): Document
Bind an event handler for one or more event names to document
@returns : document
Examples
off('click', () => {})
off('click', () => {}, { passive: true })
off(['mouseenter', 'touchstart'], () => {})
# on
on<E extends EventName>(elm: EventTarget, eventNames: E | E[], handler: EventHandler, options?: any): () => elm
Bind an event handler for one or more event names on a given DOM element.
@returns : function to remove added event handlers
Examples
const removeEvent = on(MyElm, 'click', someHandler)
const removeEvent = on(MyElm, 'click', someHandler, { passive: true })
const removeEvent = on(MyElm, ['mouseenter', 'touchstart'], someHandler)
When using options.when
let allowClick = false;
const removeEvent = on(MyElm, 'click', someHandler, { when: () => allowClick });
// In this case the `click` event won't trigger unless "allowClick" is `true`
When using options.delegate
const removeEvent = on(MyElm, 'click', someHandler, { delegate: '.click-me' });
// Here we listen to the `click` on MyElm, but the event will only trigger
// if the clicked target is a child of `MyElm` and matches the given selector ('.click-me').
// `this` and currentTarget, will match the current ".click-me" element
A combination of options
const removeEvent = on(MyElm, 'click', someHandler, {
delegate: '.click-me',
when: () => allowClick,
once: true
});
// In this scenario a MyElm '.click-me' child element will trigger the event handler,
// but only if the condition of `when` returns true ("allowClick" is `true`) and the
// event will trigger only once (event will be removed when the conditions for when
// and delegate have been fulfilled).
Types
type OnOptions = AddEventListenerOptions & {
// A selector that defines which element is the actual target of the event
delegate?: string
// A method that returns true when the event should trigger
// Combined with `once`, it will only remove the handler when `when()` resolves to true)
when?: (event: ActualEvent) => boolean
};
on<E extends EventName>(eventNames: E | E[], handler: EventHandler, options?: any): () => Document
Bind an event handler for one or more event names on document
.
@returns : function to remove added event handlers
Examples
const removeEvent = on('click', someHandler)
const removeEvent = on('click', someHandler, { passive: true })
const removeEvent = on(['mouseenter', 'touchstart'], someHandler)
When using options.when
let allowClick = false;
const removeEvent = on('click', someHandler, { when: () => allowClick });
// In this case the `click` event won't trigger unless "allowClick" is `true`
When using options.delegate
const removeEvent = on('click', someHandler, { delegate: '.click-me' });
// Here we listen to the `click` on but the event will only trigger
// if the clicked target matches the given selector ('.click-me').
// `this` and currentTarget, will match the current ".click-me" element
A combination of options
const removeEvent = on('click', someHandler, {
delegate: '.click-me',
when: () => allowClick,
once: true
});
// In this scenario a '.click-me' child element will trigger the event handler,
// but only if the condition of `when` returns true ("allowClick" is `true`) and the
// event will trigger only once (event will be removed when the conditions for when
// and delegate have been fulfilled).
Types
type OnOptions = AddEventListenerOptions & {
// A selector that defines which element is the actual target of the event
delegate?: string
// A method that returns true when the event should trigger
// Combined with `once`, it will only remove the handler when `when()` resolves to true)
when?: (event: ActualEvent) => boolean
};
# outerSize
outerSize(elm: any): {
height: number
width: number
}
Find the size of a DOM element, document or window including borders.
(Getting the size of the viewport if document
is given)
@returns : Object describing width and height of the element
Examples
// <div style="width: 200px; height: 300px; margin: 10px; border: 2px solid;" />
outerSize(div) // --> { width: 224, height: 324 }
outerSize(document) // --> [size of the viewport]
# parseSelector
parseSelector(selector: string): SelectorParsing
Parses CSS a selector string into a structured object
@returns : The attribute parsing mapping
parseSelector('.my-elm[name=test]') // --> { tagName: 'div', attributes: { name: 'test', class: 'my-elm' }, attributeList: ['name', 'class'] }
parseSelector('input[type=submit]') // --> { tagName: 'input', attributes: { type: 'submit' }, attributeList: ['type'] }
Types
type AttributeMapping = Record<string, string | 'true'> & {
class?: Set<string>
};
type SelectorParsing = {
attributeList: string[]
attributes: Record<string, string>
tagName: string
};
# position
position(elm: any): PositionData
Get the current absolute position of a DOM element and optionally also the relative position (position relative to offset parent)
@returns : the position information of the element
Examples
// Returns a 0 position
position(null);
// Basically returns the size of the element, as top and left will be 0
position(document.documentElement);
position(document.body);
// Get the position of a given element
position(MyElm);
Types
type Position = {
// Number of pixels from the top to the bottom side of the element
bottom: number
// Number of pixels from the left
left: number
// Number of pixels from the left to the right side of the element
right: number
// Number of pixels from the top
top: number
};
type PositionData = Position & {
// Position relative to the offset parent
relative?: Position
};
# prepend
prepend(elm: Element, insertElm: any): Element | null
Append DOM element or plain HTML to the beginning of a given DOM element
@returns : The inserted child element
Examples
prepend(MyNode, NodeToPrepend)
prepend(MyNode, '<span>prepended</span>')
prepend(MyNode, '.my-prepended-element')
# previousSiblings
previousSiblings(elm: Element): Element[]
Get all sibling elements before a given DOM element in the structure
@returns : Collection of sibling elements
Examples
previousSiblings(someElement);
# removeClass
removeClass(elm: any, classNames: string | string[]): elm
Remove one or multiple class names from a DOM element
@returns : Returns element given in 'elm'
Examples
// <div class="active open" />
removeClass(MyNode, 'active') // --> <div class="open" />
removeClass(MyNode, ['active', 'open']) // --> <div class="" />
# replaceClass
replaceClass(elm: any, classNames: string | string[], replacements: string | string[]): Element | null
Replaces css class with another on a DOM element.
@returns : Returns element given in 'elm'
Examples
// <div class="active open" />
replaceClass(MyNode, 'active', 'inactive') // --> <div class="inactive open" />
replaceClass(MyNode, ['active', 'open'], ['inactive', 'closed']) // --> <div class="inactive closed" />
replaceClass(MyNode, 'active', ['inactive', 'removed']) // --> <div class="inactive removed open" />
# replaceNode
replaceNode(elm: Node, replacement?: any): Node | void
Replace a given DOM element with another DOM element or plain HTML string
@returns : The value given in elm
Examples
// <div><span id='a' /></div>
replaceNode(document.getElementById('a'), document.createElement('p')) // --> <div><p /></div>
replaceNode(document.getElementById('a'), 'p.p') // --> <div><p class="p" /></div>
# scrollInfo
scrollInfo(elm?: any): ScrollInfo
Gather the current scroll position information of a DOM element or the window
@returns : The scroll information
Examples
scrollInfo(window)
scrollInfo(document)
scrollInfo(MyElm)
Types
type ScrollInfo = {
x: number
xMax: number
xPct: number
y: number
yMax: number
yPct: number
};
# scrollParent
scrollParent(elm: Element): Element | HTMLElement | null
Get the parent element that has scrolling
@returns : The scroll parent or the viewport
Examples
scrollParent(document.body) // --> `<html>`
// <div style="overflow:auto"><p id="P" /></div>
scrollParent(document.getElementById('P')) // --> `<div>`
// <div style="overflow:auto"><p id="P" style="position: fixed" /></div>
scrollParent(document.getElementById('P')) // --> `<html>`
// <div style="overflow:auto"><p id="P" style="position: absolute" /></div>
scrollParent(document.getElementById('P')) // --> `<html>`
// <div style="overflow:auto; position: relative"><p id="P" style="position: absolute" /></div>
scrollParent(document.getElementById('P')) // --> `<div>`
# selectorToHTML
selectorToHTML(selector: string): string
Converts a given CSS selector into HTML
(No this is not an Emmet substitute, so it is limited to only one element)
@returns : The parsed HTML
Examples
selectorToHTML('#id.class-name'); // --> '<div id="id" class="class-name" />'
# siblings
siblings(elm: Element): Element[]
Get all sibling elements of a given DOM element
@returns : Collection of sibling elements
Examples
siblings(someElement);
# toDOM
toDOM(html: string): HTMLCollection | null
Convert HTML into DOM node(s)
@returns : DOM elements that the HTML represented
Examples
// HTML cannot be parsed easily
toDOM('<html><body><div /></body></html>'); // --> null
// Convert a given HTML string to HTML
toDOM('<div><a>link</a></div>')
// --> <div><a>link</a></div>
# toggleClass
toggleClass(elm: any, classNames: string | string[], force?: boolean): elm
Toggles (add/remove) one or multiple class names on a DOM element
@returns : The given elm
Examples
// <div class="active open" />
toggleClass(MyNode, 'active') // --> <div class="open" />
toggleClass(MyNode, ['active', 'open']) // --> <div class="active" />
// <div class="active open" />
toggleClass(MyNode, 'active', true) // --> <div class="active open" />
toggleClass(MyNode, 'active', false) // --> <div class="open" />
# trigger
trigger(elm: EventTarget, eventNames: string | string[], data?: unknown): elm
Trigger one or more events on a given DOM element.
@returns : The 'elm' (or document)
Examples
trigger(MyElm, 'click')
trigger(MyElm, 'my-event', { SomeEntry: true })
trigger(eventNames: string | string[], data?: unknown): Document
Trigger one or more events on Document.
@returns : The 'elm' (or document)
Examples
trigger('click')
trigger('my-event', { SomeEntry: true })
# uniqueNodeList
uniqueNodeList<T extends Element>(args: any[]): T[]
Make a unique list of Elements from on or multiple Element collections
(usually as a result of some element selection method)
@returns : The unique list of elements
Examples
const byClassName = (selector) => document.getElementsByClassName(selector)
// Using a single selector
findUniqueNodeCollection('my-elements', byClassName);
// Using multiple selectors
findUniqueNodeCollection(['.my-element', 'sone-other-elements'], byClassName);
# vendorPrefixed
vendorPrefixed(str: string): VendorPrefixing
Add vendor prefixes to a string
@returns : Array of the various vendor vendorPrefixed versions of the string
Examples
vendorPrefixed('backface-visibility')
// [
// { prefix: '', js: 'backfaceVisibility', css: 'backface-visibility' }
// { prefix: 'webkit', js: 'webkitBackfaceVisibility', css: '-webkit-backface-visibility' }
// { prefix: 'moz', js: 'mozBackfaceVisibility', css: '-moz-backface-visibility' }
// { prefix: 'ms', js: 'msBackfaceVisibility', css: '-ms-backface-visibility' }
// { prefix: 'o', js: 'oBackfaceVisibility', css: '-o-backface-visibility' }
// ]
Types
type VendorPrefixing = [{
css: string
js: string
prefix: ''
}, {
css: `-webkit-${string}`
js: `webkit${string}`
prefix: 'webkit'
}, {
css: `-moz-${string}`
js: `moz${string}`
prefix: 'moz'
}, {
css: `-ms-${string}`
js: `ms${string}`
prefix: 'ms'
}, {
css: `-o-${string}`
js: `o${string}`
prefix: 'o'
}];
# viewport
viewport(elm?: any): HTMLElement
Get the current viewport element (scrolling element) of the current document, from a given element
@returns : The viewport element
Examples
// Get the viewport of the current document
viewport();
// Get the viewport of the current window
viewport(window);
// Get the viewport of a given element
viewport(someElementInSomeDocument);
# visible
visible(elm: HTMLElement): boolean
Test if a given DOM element is visible.
@returns : Is the element visible for the user
Examples
visible(document.body) // --> true
visible(MyNormalElement) // --> true
visible(myZeroHeightElement) // --> false
visible(myZeroWidthElement) // --> false
visible(myNoDisplayElement) // --> false
visible(myNoVisibilityElement) // --> false
# wrap
wrap(elm: Element, wrapping: any): Element | null
Wrap a given element in the given HTML, selector or element
@returns : If the wrapping was successful or not
Examples
wrap(document.documentElement, '<div />') // --> false - you cannot wrap the <html> element
wrap(MyElm, document.createElement('div')) // --> true
wrap(MyElm, '<div class="wrap-element"><span><b /></span></div>') // --> true - element inserted into the <b> tag
wrap(MyElm, '.wrap-element') // --> true