Skip to content

Commit 9d6b57b

Browse files
committed
feat: createDomElement utility
1 parent b7b3750 commit 9d6b57b

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

js/util.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,75 @@ export function getWikis( withSpacers, withVirtuals ) {
164164
export function getNativeSettings() {
165165
return chrome && chrome.storage || window.storage;
166166
}
167+
168+
169+
/**
170+
* @typedef {Object} DomElementFactoryOptions
171+
* @property {string[]?} [classes]
172+
* @property {string} [text]
173+
* @property {string|HTMLElement|HTMLElement[]} [html]
174+
* @property {Record<string, string|undefined|boolean|number>} [attributes]
175+
* @property {Partial<CSSStyleDeclaration>} [style]
176+
* @property {Partial<{
177+
* [ P in keyof HTMLElementEventMap ]: ( ( event: HTMLElementEventMap[ P ] ) => void ) | ( () => void )
178+
* }>} [events]
179+
* @property {HTMLElement} [appendTo]
180+
* @property {HTMLElement} [prependTo]
181+
*/
182+
183+
/**
184+
* @param {keyof HTMLElementTagNameMap} tag
185+
* @param {DomElementFactoryOptions} options
186+
* @return {HTMLElement}
187+
*/
188+
export function createDomElement( tag, options ) {
189+
const result = document.createElement( tag );
190+
if ( options.text ) {
191+
result.innerText = options.text;
192+
}
193+
if ( options.html ) {
194+
if ( typeof options.html === 'string' ) {
195+
result.innerHTML = options.html;
196+
} else if ( Array.isArray( options.html ) ) {
197+
for ( const element of options.html ) {
198+
result.appendChild( element );
199+
}
200+
} else {
201+
result.appendChild( options.html );
202+
}
203+
}
204+
if ( options.classes ) {
205+
result.classList.add( ...options.classes );
206+
}
207+
if ( options.attributes ) {
208+
for ( const key in options.attributes ) {
209+
const value = options.attributes[ key ];
210+
if ( value !== undefined && value !== null ) {
211+
result.setAttribute( key, `${value}` );
212+
}
213+
}
214+
}
215+
if ( options.style ) {
216+
for ( const key in options.style ) {
217+
const value = options.style[ key ];
218+
if ( value !== undefined && value !== null ) {
219+
result.style[ key ] = value;
220+
}
221+
}
222+
}
223+
if ( options.events ) {
224+
for ( const name in options.events ) {
225+
const listener = options.events[ name ];
226+
if ( listener ) {
227+
result.addEventListener( name, listener );
228+
}
229+
}
230+
}
231+
if ( options.appendTo ) {
232+
options.appendTo.appendChild( result );
233+
}
234+
if ( options.prependTo ) {
235+
options.prependTo.prepend( result );
236+
}
237+
return result;
238+
}

0 commit comments

Comments
 (0)