DomHelper
A static utility class for DOM element creation, querying, and manipulation. It provides createElement to build element trees from DomConfig objects, and includes helpers for measuring, focusing, scrolling, and synchronizing DOM structures.
DomHelper.createElement({
tag : 'div',
className : 'parent',
style : 'background: red',
children : [
{ tag: 'div', className: 'child' },
{ tag: 'div', className: 'child' }
]
});
Useful functions
| Function | Description |
|---|---|
| createElement | Create an element from a DomConfig object |
| sync | Sync a DomConfig to an existing DOM tree |
| isVisible | Check whether an element is visible |
See also
- DomConfig - Element configuration object
- EventHelper - DOM event utilities
Properties
Properties are getters/setters or publicly accessible variables on this class-
Returns active element checking shadow dom too
-
Check if the currently used theme is a dark theme, by checking the
color-schemeproperty of.b-widget. -
Get the current themes primary color (by reading it from
document.body) -
Measures the scrollbar width using a hidden div. Caches result
-
Returns the maximum scroll range the browser can correctly manage. This value is browser-specific and typically in the millions of pixels. This answer is not intended to be a precise value but a safe and reliable value to avoid encountering browser limitations.
-
A theme information object about the current theme. Note, when using Bryntum widgets inside a shadowRoot context, you need to use getThemeInfo and pass a context element.
-
Set to
falseto not show focus renditions when using keyboard
Functions
Functions are methods available for calling on the class-
Adds the passed string as a space-separated value to the passed attribute in the passed element.
-
Align the passed element with the passed target according to the align spec.
-
Resolves child element from point in the passed element's coordinate space.
-
Create element(s) from a template (html string). Note that
textNodes are discarded unless therawoption is passed astrue.If the template has a single root element, then the single element will be returned unless the
arrayoption is passed astrue.If there are multiple elements, then an Array will be returned.
-
Resolves element from point, checking shadow DOM if required
-
Reads computed style from the element and returns the animation duration for any attached animation in milliseconds
-
Returns element animations
-
Returns common widget/node ancestor for from/to arguments
-
Returns an object with the parse style values for the top, right, bottom, and left components of the given edge style.
The return value is an object with
top,right,bottom, andleftproperties for the respective components of the edge style, as well aswidth(the sum ofleftandright) andheight(the sum oftopandbottom). -
Internal convenience fn to allow specifying either an element or a CSS selector to retrieve one
-
Returns the specified element of the given
event. If theeventis anElement, it is returned. Otherwise, theeventNameargument is used to retrieve the desired element property fromevent(this defaults to the'target'property). -
Returns a dynamic property from a DOM element given a dot-path name. All of these properties are stored on a
$bryntumobject property lazily added to theelement.For example:
const v = DomHelper.getExpando(el, 'foo');Is equivalent to:
const v = el.$bryntum?.foo;Also:
const v = DomHelper.getExpando(el, 'foo', 42);Is equivalent to:
const v = (el.$bryntum && 'foo' in el.$bryntum) ? el.$bryntum.foo : 42;The
keyparameter can also be a dot-path, like so:const v = DomHelper.getExpando(el, 'foo.bar', 42);Is equivalent to:
const v = (el.$bryntum?.foo && 'bar' in el.$bryntum.foo) ? el.$bryntum.foo.bar : 42; -
Returns a lazily created object attached to
elementgiven itskey. Thekeyparameter can be a simple name or a dot-path.For example:
const obj = DomHelper.getExpandos(el, 'foo');Is equivalent to:
const obj = (el.$bryntum || (el.$bryntum = Object.create(null))).foo || (el.$bryntum.foo = Object.creat(null)); -
Returns extremal (min/max) size (height/width) of the element in pixels
-
Returns an object describing the focus and keyboard navigation aspects of a given element.
By default, it returns the general abilities of the element to be focused, not taking into account whether the element is currently visible.To check whether the element is currently focusable in the UI, pass
trueas the second parameter. -
Returns the
idof the passed element. Generates a uniqueidif the element does not have one. -
Reads computed style from the element and returns transition duration for a given property in milliseconds
-
Gets theme information about the currently active theme by reading CSS custom properties from the
.b-theme-infoclass.The method creates a temporary DOM element with the
b-theme-infoclass, reads all CSS custom properties that start with--b-theme-, converts them to camelCase property names, and returns them as an object.Example theme CSS:
.b-theme-info { --b-theme-name : "SvalbardDark"; --b-theme-filename : "svalbard-dark"; --b-theme-button-rendition : "text"; --b-theme-label-position : "align-before"; --b-theme-overlap-label : "false"; }This would result in:
{ name : "SvalbardDark", filename : "svalbard-dark", buttonRendition : "text", labelPosition : "align-before", overlapLabel : false // String "true"/"false" values are converted to boolean } -
This method checks that the passed target is visible in all viewports
-
Handles the content provided by a React component for the widget.
-
Handles the React header element by processing JSX content within the widget.
-
Handles the content provided by a Vue component for the widget.
-
Highlights the passed element or Rectangle according to the theme's highlighting rules. Usually an animated framing effect.
The framing effect is achieved by adding the CSS class
b-fx-highlightwhich references akeyframesanimation namedb-fx-highlight-animation. You may override the animation name referenced, or the animation itself in your own CSS. -
Checks if an element clips its content.
-
Returns true if element has opened shadow root
-
Returns true if DOM Event instance is passed. It is handy to override to support Locker Service.
-
Returns
trueif the passed element accepts keystrokes to edit its contents. -
Returns
trueif the provided value is likely a DOM element. If the element can be assured to be from the same document,instanceof Elementis more reliable. -
Returns
trueif the passed element is focusable either programmatically or through pointer gestures. -
Returns the rectangle of the element or event which is currently visible in the browser viewport, i.e. user can find it on screen, or
falseif it is scrolled out of view. -
Returns
trueif the provided value is likely a DOM node. If the node can be assured to be from the same document,instanceof Nodeis more reliable. -
Returns
trueif the provided element is an instance of React Element. -
Returns
trueif the passed element is deeply visible. Meaning it is not hidden usingdisplayorvisibilityand no ancestor node is hidden. -
Returns
trueif the provided configuration object is valid for Vue processing. -
Converts the passed id to an id valid for usage as id on a DOM element.
-
Merges specified source DOM config objects into a
destobject. -
Updates in-place a DOM config object whose
childrenproperty may be an object instead of the typical array. The keys of such objects become thereferenceproperty upon conversion. -
Splits a style string up into object form. For example
'font-weight:bold;font-size:150%'would convert to{ font-weight : 'bold', font-size : '150%' } -
Returns string percentified and rounded value for setting element's height, width etc.
-
Removed the passed string as a space-separated value from the passed attribute in the passed element.
-
Removes the passed CSS classes from all descendants of the passed element.
-
Removes a dynamic property from a DOM element given a dot-path name.
-
resetScrollBarWidth( )static
Resets DomHelper.scrollBarWidth cache, triggering a new measurement next time it is read
-
Sets attributes passed as object to given element
-
Stores a dynamic property on a DOM element given a dot-path name. All of these properties are stored on a
$bryntumobject property lazily added to theelement.For example:
DomHelper.setExpando(el, 'foo', 42);Is equivalent to:
(el.$bryntum || (el.$bryntum = Object.create(null))).foo = 42; -
Sets a CSS length style value.
-
Changes the theme to the passed theme name if possible.
Theme names are case-insensitive. The
hrefused is all lower case.To use this method, the
<link rel="stylesheet">must use the default, Bryntum-supplied CSS files where thehrefend with<themeName>.css, so that it can be found in the document, and switched out for a new link with the modifiedhref. The newhrefwill use the same path, just with thethemeNameportion substituted for the new name.If no
<link>with that name pattern can be found, an error will be thrown.If you use this method, you must ensure that the theme files are all accessible on your server.
Because this is an asynchronous operation, a
Promiseis returned. The theme change event is passed to the success function. If the theme was not changed, because the theme name passed is the current theme, nothing is passed to the success function.The theme change event contains two properties:
prevThe previous Theme name.themeThe new Theme name.
-
Animates the specified element to slide it into view within the visible viewport of its parentElement from the direction of movement.
So in a left-to-right Widget,
direction1 means it slides in from the right anddirection-1 means it slides in from the left. RTL reverses the movement.See the forward/backward navigations in DatePicker for an example of this in action.
If "next" should arrive from below and "previous" should arrive from above, add the class
b-slide-verticalto the element. -
Strips the tags from a html string, returning text content.
DomHelper.stripTags('<div class="custom"><b>Bold</b><i>Italic</i></div>'); // -> BoldItalic -
Sync one source element attributes, children etc. to a target element. Source element can be specified as a html string or an actual HTMLElement.
NOTE: This function is superseded by DomSync.sync(), which works with DOM configs. For most usecases, use it instead.
-
Syncs attributes from sourceElement to targetElement.
-
Sync traversing children
-
Sync content (innerText) from sourceElement to targetElement
-
toggleLightDarkTheme( )static
Toggles between light and dark themes. Does not check if the theme is actually available, only does a string replace on the current themes filename for light/dark.
-
Dispatches a MouseEvent of the passed type to the element at the visible centre of the passed element. If the element is not in view, the event is not dispatched.
-
Converts a name/value pair of a style name and its value into the canonical (hyphenated) name of the style property and a value with the
defaultUnitsuffix appended if no unit is already present in thevalue.For example:
const [property, value] = DomHelper.unitize('marginInlineStart', 50); console.log(property, value);> margin-inline-start 50px -
Waits for the specified target element to be visible and in view, and not within an animation.
If the specified selector is not immediately visible and outside of any animations, this method will return a Promise which, if the element becomes available in the specified
maxWait, resolves to the targetHTMLElement.If the element does not become available after the
maxWait, the Promise will reject.If the selector ends with
?, or themaxWaitis negative, the target element is optional and if not found,undefinedis returned. -
Adds a CSS class to an element during the specified duration
-
Applies specified style to the passed element. Style can be an object or a string.
-
Adds or removes the
classescontained in the specified object based on the truthy or falsy value of that key.For example:
DomHelper.assignClasses(element, { 'b-class-one' : 1 // class will be added 'b-class-two' : 0 // class will be removed }); -
Returns a style value or values for the passed element.
-
Replaces the passed element's
classNamewith the class names passed in either Array or String format or Object.This method compares the existing class set with the incoming class set and avoids mutating the element's class name set if possible.
This can avoid browser style invalidations.
-
Toggle multiple classes in elements classList. Helper for toggling multiple classes at once.
-
Applies the key state of the passed object or DomClassList to the passed element.
Properties with a falsy value mean that property name is removed as a class name.
Properties with a truthy value mean that property name is added as a class name.
This is different from syncClassList. That sets the
classNameof the element to the sum of all its truthy keys, regardless of what the pre-existing value of theclassNamewas, and ignoring falsy keys.This selectively updates the classes in the
className. If there is a truthy key, the name is added. If there is a falsy key, the name is removed. -
Appends element to parentElement.
-
Creates an Element, accepts a DomConfig object. Example usage:
DomHelper.createElement({ tag : 'table', // defaults to 'div' className : 'nacho', html : 'I am a nacho', children : [ { tag: 'tr', ... }, myDomElement ], parent : myExistingElement // Or its id style : 'font-weight: bold;color: red', dataset : { index: 0, size: 10 }, tooltip : 'Yay!', ns : 'http://www.w3.org/1999/xhtml' }); -
Inserts an
elementbeforebeforeElementininto. -
Inserts an
elementat first position ininto. -
Measures a relative size, such as a size specified in
emunits for the passed element. -
Measures the text width using a hidden div
-
Get elements X offset within a containing element
-
Gets elements X and Y offset within containing element as an array [x, y]
-
Get elements Y offset within a containing element
-
Get elements X position on page
-
Get elements Y position on page
-
Returns the
xfrom the element'stranslate: x yvalue in pixels. -
Gets both X and Y coordinates as an array [x, y]
-
Returns the
yfrom the element'stranslate: x yvalue in pixels. -
Increase X position
-
Increase Y position
-
Increase
Xtranslation -
Increase
Yposition -
Set element's style
left. -
Set element's
scale. -
Set element's style
top. -
Set element's
Xtranslation in pixels (keepinYtranslation as is). -
Set elements
XandYtranslation in pixels. -
Set element's
Ytranslation in pixels (keepingXtranslation as is). -
Returns all child elements (not necessarily direct children) that matches
selector.If
selectorstarts with'>'or'# ', then all components of theselectormust match inside ofelement. The scope selector,:scopeis prepended to the selector (and if#was used, it is removed).These are equivalent:
DomHelper.children(el, '# .foo .bar'); el.querySelectorAll(':scope .foo .bar');These are also equivalent:
DomHelper.children(el, '> .foo .bar'); el.querySelectorAll(':scope > .foo .bar'); -
Looks at the specified
elementand all of its children for the one that first matchesselector. -
Iterates over the direct child elements of the specified element.
-
Iterates over each result returned from
element.querySelectorAll(selector). Can also be called with only two arguments, in which case the first argument is used as selector and document is used as the element. -
Gets the first direct child of
elementthat matchesselector. -
Checks if
elementhas any child that matchesselector. -
Checks if childElement is a descendant of parentElement (contained in it or a sub element)
-
Removes each element returned from
element.querySelectorAll(selector). -
Retrieves all parents to the specified element.
Type definitions
-
Focusabilityinternal
An immutable object that describes the various aspects of an element's focus and keyboard navigation.
Properties
- focusable : Boolean
Indicates that the element is focusable by keyboard navigation or programmatic means.
- natural : Boolean
Indicates that the element is naturally focusable without assigning a
tabIndex. - programmatic : Boolean
Indicates that the element is programmatically focusable (i.e.,
tabIndex = -1). - tabbable : Boolean
Indicates that the element is reachable by keyboard navigation, e.g. via the TAB key.
- focusable : Boolean
-
A theme information object about the current theme.
Theme information object containing metadata about the active theme. The theme information is read from CSS custom properties defined in the
.b-theme-infoclass.Example CSS:
.b-theme-info { --b-theme-name : "SvalbardDark"; --b-theme-filename : "svalbard-dark"; --b-theme-button-rendition : "text"; --b-theme-label-position : "align-before"; --b-theme-overlap-label : "false"; }Properties
- name : String
The display name of the current theme (e.g., "SvalbardDark")
- filename : String
The filename/identifier of the theme (e.g., "svalbard-dark")
- buttonRendition : String
The button rendering style for the theme (e.g., "text", "outlined", "filled")
- labelPosition : String
The default label position for form fields (e.g., "align-before", "above")
- overlapLabel : Boolean
Whether labels should overlap with fields
- name : String
-
An object that describes a DOM element. Used for example by createElement() and by DomSync.sync().
DomHelper.createElement({ class : { big : true, small : false }, children : [ { tag : 'img', src : 'img.png' }, { html : '<b style="color: red">Red text</b>' } ] });Properties
- tag : String'div'
Tag name, for example 'span'. If this is passed as
'#fragment', a DocumentFragment will be created. - parent : HTMLElement
Parent element
- nextSibling : HTMLElement
Element's next sibling in the parent element
- class : String/Object
CSS classes, as a string or an object (truthy keys will be applied)
- className : String/Object
Alias for
class - style : String/Object
Style, as a string or an object (keys will be hyphenated)
- elementData : Object
Data object stored as an expando on the resulting element
- dataset : Object
Dataset applied to the resulting element
- children : DomConfig[]/Object<String, DomConfig>/String[]/HTMLElement[]
Child elements, as an array that can include DomConfigs that will be turned into elements, plain strings that will be used as text nodes or existing elements that will be moved. Also accepts an object map of DomConfigs, but please note that it cannot be used with
DomHelper.createElement() - html : String
Html string, used as the resulting elements
innerHTML. Mutually exclusive with thechildrenproperty - tooltip : TooltipConfig/String
Tooltip config applied to the resulting element
- text : String
Text content, XSS safe when you want to display text in the element. Mutually exclusive with the
childrenproperty - id : String
Element's
id - href : String
Element's
href - ns : String
Element's namespace
- src : String
Element's
src
- tag : String'div'
-
An object that describes a vue component configuration.
{ vue : true is : 'VueWidget' bind : { prop1: 'value1', prop2: 'value2' } on : { myclick: handleMyClick } } -
Placeholder type for React JSX nodes in plain JS