@xan105/vanilla-query
v1.14.1
Published
DOM manipulation and traversal in Vanilla JS with chaining
Maintainers
Readme
About
DOM manipulation and traversal in Vanilla JS with chaining. Like jQuery but with a Vanilla flavor 😋.
📦 Scoped @xan105 packages are for my own personal use but feel free to use them.
Example
import { whenReady, html, $select, $selectAll } from "./path/to/vq.js"
await whenReady(); //DOM is ready
//Creating DocumentFragment
function component(){
return html({
elements: ["ul", "li"],
attributes: ["class"],
dataAttributes: true
})`
<ul class="foo">
<li>foo</li>
<li data-foo="bar">bar</li>
</ul>
`
}
$select(#mydiv).add(component());
//DOM Manipulation
$select("#div .child[data-attr='val']").$css("background","red").$text("Hello World");
const el = $select("#div");
el.$hide();
el
.$css("background","blue")
.$fadeIn(400)
.then(function(){
this.$css("background","green")
}.bind(el));
$selectAll(li)[0].$text("0");
$selectAll(li).forEach(el => el.$css("color","black"));
$select("#div .child").$css("background","red").$select(".child").$selectAll("p");Install
npm i @xan105/vanilla-query💡 The bundled library and its minified version can be found in the ./dist folder.
Via importmap
Create an importmap and add it to your html:
<script type="importmap">
{
"imports": {
"@xan105/vanilla-query": "./path/to/node_modules/@xan105/vanilla-query/dist/vq.min.js"
}
}
</script>
<script src="./index.js" type="module"></script>
</body>
</html>index.js:
import { whenReady } from "@xan105/vanilla-query"
await whenReady();
console.log("Hello world !");API
⚠️ This module is only available as an ECMAScript module (ESM) and is intended for the browser.
Named export
whenReady(): Promise<void>Resolves when the DOM is ready.
whenDefined(components?: { name: HTMLElement Constructor, ... }): Promise<void>Resolves when all Web Components (CustomElements) are defined.
whenLoaded(components?: { name: HTMLElement Constructor, ... }): Promise<void>A shorthand for calling
whenReady()+whenDefined().html(options?: Sanitizer | SanitizerConfig | string)`string`: DocumentFragmentCreate a DocumentFragment from the given html string template. The function returns a template literal (template string) "tagFunction" which returns the DocumentFragment.
options
A Sanitizer or SanitizerConfig object which defines what elements of the input will be allowed or removed, or the string "default" for the default configuration.
If omitted the default configuration is used.
⚠️ The method removes any elements and attributes that are considered XSS-unsafe, even if allowed by a passed sanitizer.
Example
const sanitizer = new Sanitizer({elements: ["div", "p", "button", "script"]}); // script is unsafe and will be removed const template = html(sanitizer)` <div> <p>Paragraph to inject into DOM. <button onclick="alert('You clicked the button!')">Click me</button> </p> <script src="path/to/a/module.js" type="module"><\/script> <p data-id="123">Para with <code>data-</code> attribute</p> </div> `;htmlUnsafe(options?: Sanitizer | SanitizerConfig | string)`string`: DocumentFragment⚠️ The suffix "Unsafe" in the method name indicates that it does not enforce removal of all XSS-unsafe HTML entities.
Otherwise same as
html(options)`string`:DocumentFragmentabove.createSanitizer(SanitizerConfig): SanitizerApply a SanitizerConfig to the default Sanitizer configuration.
Returns a Sanitizer instance.
css`string`: CSSStyleSheetCreate a CSS style sheet from the given css string template. NB: This is a template literal (template string) "tagFunction".
adoptStyleSheet(sheet, root = document)Add a CSSStyleSheet to the given ShadowRoot "root" or the document if omitted.
define(el: HTMLElement | Unknown): HTMLElement | UnknownAdd the following helpers (see below) to the given HTMLElement.
$select(query: string, scope?: HTMLElement = document): HTMLElement | undefinedSelect HTMLElement matching the given query selector; relative to the given scope (document if omitted). Add the following helpers (see below) to the returned HTMLElement.
NB: If the targeted element is a HTML template tag then its cloned instance is returned.
$selectAll(query: string, scope?: HTMLElement = document): HTMLElement[] | undefined[]Select every HTMLElement matching the given query selector; relative to the given scope (document if omitted). Add the following helpers (see below) to every returned HTMLElement.
NB: If some of the targeted elements are a HTML template tag then their cloned instance are returned.
Helpers
$addClass(...names: string[]): HTMLElementAdd given class name(s).
$removeClass(...names: string[]): HTMLElementRemove given class name(s).
$toggleClass(...names: string[]): HTMLElementToggle given class name(s): remove if exist and add it otherwise.
$hasClass(name: string): booleanReturn whether the HTMLElement has the given class name or not.
$html(value?: string): HTMLElement | stringInsert a string of HTML into the DOM as a subtree of the element. If value is omitted then it returns the element's DOM as an HTML string.
$css(name: string, value?: string): HTMLElement | stringSet CSS inline style name property to the given value if any. Otherwise returns the current value.
$style(sheet: object): HTMLElementSet CSS inline style from a sheet object representation as follows:
{ name: "value", ... }$text(value?: string): HTMLElement | stringSet text content to the given value if any. Otherwise returns the current value.
$attr(name: string, value?: string): HTMLElement | stringSet attribute name to the given value if any. Otherwise returns the current value.
$toggleAttr(...names: string[]): HTMLElementToggle given attribute name(s): remove if exist and add it otherwise.
$removeAttr(...names: string[]): HTMLElementRemove given attribute name(s).
$empty(): HTMLElementRemove all children of the HTMLElement.
$show(): HTMLElementShow the HTMLElement.
$hide(): HTMLElementHide the HTMLElement.
$isHidden(): booleanReturn whether the HTMLElement is visible or not.
$on(eventName: string, listener: function): voidAdd an EventListener and keep track of the listener inside the Symbol property
events. Calling$off(eventName)will remove every known listener/handler for that event.$once(eventName: string, listener: function): voidAdd an EventListener which is automatically removed when the listener is invoked.
$off(eventName: string, listener?: function): voidalias: $removeListener
Remove specified listener/handler for the given event. If omitted remove every known listener/handler for the given event.
$removeAllListeners(eventName?: string[]): voidRemove every known listener/handler or those of the specified eventName.
$click(listener?: function): voidAdd a click event listener or trigger it if omitted.
$contextmenu(listener?: function): voidAdd a right click event (contextmenu) listener or trigger it if omitted.
$trigger(name: string): voidTrigger given HTML event name.
$select(query: string): HTMLElement | nullSee
$select()above but the scope is the current element.$selectAll(query: string): HTMLElement[] | null[]See
$selectAll()above but the scope is the current element.$add(el: HTMLElement | string | DocumentFragment): HTMLElementAdd a new instance of the given element or DocumentFragment to the end of the list of children of the current element.
If
elis astringthen an element will be created from the assumed tag name.If
elis aDocumentFragmentthen the fragment is appended to the current element and it returns the current element.$parent(query?: string): HTMLElement | nullReturn the closest parent element that matches the specified query selector. If omitted return the parent node.
$prev(): HTMLElement | nullReturn the previous element if any.
$next(): HTMLElement | nullReturn the next element if any.
$prevUntilVisible(): HTMLElement | nullReturn the previous visible element if any.
$nextUntilVisible(): HTMLElement | nullReturn the next visible element if any.
$fadeOut(duration?: number = 400): Promise<void>Fade out animation to the current HTMLElement.
$fadeIn(duration?: number = 400): Promise<void>Fade in animation to the current HTMLElement.
