jj
    Preparing search index...

    Class JJE<T>

    Wraps a DOM Element (which is a descendant of Node).

    This class provides a wrapper around the native Element interface, adding fluent API methods for attribute manipulation, class handling, and event binding.

    Type Parameters

    • T extends Element = Element

    Hierarchy

    • JJNx<T>
      • JJE
    Index

    Constructors

    • Creates an instance of JJE.

      Type Parameters

      • T extends Element = Element

      Parameters

      • ref: T

        The Element to wrap.

      Returns JJE<T>

      If ref is not an Element.

      • JJHE for wrapping HTMLElements
      • JJSE for wrapping SVGElements
      • JJME for wrapping MathMLElements

    Accessors

    • get children(): Wrapped[]

      Gets the child nodes wrapped in the most specific JJ wrappers available.

      Returns Wrapped[]

      The wrapped child nodes.

      Returns an empty array when this node has no children.

      const el = JJHE.create('div').addChild('hello', JJHE.create('span'))
      const children = el.children // [JJT, JJHE]
    • get parent(): Wrapped | null

      Gets the parent node wrapped in the most specific JJ wrapper available.

      Returns Wrapped | null

      The wrapped parent node, or null if this node has no parent.

      Returns null when this node is detached and therefore has no parent.

      const text = JJT.create('hello')
      JJHE.create('div').addChild(text)
      const parent = text.parent // JJHE
    • get ref(): T

      Gets the underlying DOM object.

      Returns T

      run for fluent callbacks that can also access this same wrapped target.

    • get shadow(): JJSR<ShadowRoot> | null

      Gets a wrapper around the Element's Shadow Root, if it exists.

      Returns JJSR<ShadowRoot> | null

      A JJSR instance wrapping the shadow root, or null if no shadow root exists.

      • setShadow for creating and initializing a shadow root.
      • JJSR for ShadowRoot-specific helper methods.

    Methods

    • Appends children to this Element.

      Parameters

      • ...children: Wrappable[]

        The children to append.

      Returns this

      This instance for chaining.

      el.addChild(JJHE.tree('span', null, 'hello'))
      

      To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

    • Maps an array to children and appends them.

      Type Parameters

      • T

      Parameters

      • array: T[]

        The source array.

      • mapFn: (item: T) => Wrappable

        The mapping function returning a Wrappable.

      Returns JJE<T>

      This instance for chaining.

      node.addChildMap(['a', 'b'], item => JJHE.tree('li', null, item))
      

      To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      If array is not an array.

      If mapping the array or appending the children fails.

      • addChild for directly appending variadic children.
      • addChildren for appending a pre-built array of children.
    • Appends an array of children to this Element.

      Parameters

      • children: Wrappable[]

        The children to append.

      Returns this

      This instance for chaining.

      This is the array-based companion to addChild. To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      el.addChildren([JJHE.tree('span', null, 'hello'), ' world'])
      

      If children is not an array.

    • Adds one or more classes to the Element.

      Parameters

      • ...classNames: string[]

        The classes to add.

      Returns this

      This instance for chaining.

      el.addClass('btn', 'btn-primary')
      

      If any class name is not a string.

    • Adds multiple classes from an array of class names.

      Parameters

      • classNames: string[]

        The classes to add.

      Returns this

      This instance for chaining.

      el.addClasses(['btn', 'btn-primary'])
      

      If classNames is not an array.

      If any class name in classNames is not a string.

    • Clones and appends template-like input to this node.

      Parameters

      • template:
            | string
            | HTMLElement
            | DocumentFragment
            | HTMLTemplateElement
            | JJDF<DocumentFragment>
            | JJHE<HTMLTemplateElement>
            | JJHE<HTMLElement>

        The template source to clone and append.

      Returns this

      This instance for chaining.

      Supports HTML strings, native template sources, native Nodes, and any JJ wrapper via JJN. Wrapper inputs are unwrapped and cloned before append.

      If the template type is unsupported or a Promise was passed.

    • Creates a Text node from a string and appends it to this Node.

      Parameters

      • ...textArr: unknown[]

        The text to add. The actual text that's added follows the rules in document.createTextNode() which is basically what you get from String()

      Returns this

      This instance for chaining.

      This method is overridden in JJT to append to the existing text content instead.

      el.addText('Hello ')
      el.addText('World')
      // Behaves like document.createTextNode('Hello World') and appends it to el
      // Falsy values are converted to their string representation, except for empty string which is added as is.
      el.addText('Hello', '', 'world', null, undefined, '!!!') // Adds 6 text nodes with content 'Hello', '', 'world', 'null', 'undefined', and '!!!' respectively.
    • Clones the Node.

      Parameters

      • Optionaldeep: boolean

        If true, clones the subtree.

      Returns JJE<T>

      A new wrapped instance of the clone.

    • Finds the closest ancestor (or self) that matches a CSS selector.

      Parameters

      • selector: string

        The CSS selector to search for.

      Returns Wrapped | null

      A JJE wrapping the closest match, or null when none exists.

      Returns null when no matching ancestor is found.

      const button = JJE.from(document.querySelector('button'))
      const card = button.closest('.card')
      if (card) {
      card.addClass('has-action')
      }

      If selector is not a string.

    • Removes all children from this Element.

      Returns this

      This instance for chaining.

      el.empty()
      
    • Enables the Element by removing the disabled and aria-disabled attributes.

      Returns this

      This instance for chaining.

      • disable for the inverse operation.
      • rmAttr for generic attribute removal.
    • Finds the first element matching a selector within this Element.

      Parameters

      • selector: string

        The CSS selector.

      • required: boolean = false

        Whether to throw an error if not found. Defaults to false.

      Returns Wrapped | null

      The wrapped element, or null if not found and required is false.

      const span = el.find('span')  // Returns null if not found
      const span = el.find('span', true) // Throws if not found

      If selector is not a string or element not found and required is true.

    • Finds all elements matching a selector within this Element.

      Parameters

      • selector: string

        The CSS selector.

      Returns Wrapped[]

      An array of wrapped elements.

      const items = el.findAll('li')
      

      If selector is not a string.

    • Gets the value of an ARIA attribute.

      Parameters

      • name: string

        The ARIA attribute suffix (e.g., 'label' for 'aria-label').

      Returns string | null

      The attribute value, or null if not present.

      Automatically prepends aria- to the name.

      el.getAriaAttr('label') // gets 'aria-label'
      

      If name is not a string.

    • Gets the value of an attribute.

      Parameters

      • name: string

        The name of the attribute.

      Returns string | null

      The attribute value, or null if not present.

      If name is not a string.

    • Gets the inner HTML of the Element.

      Returns string

      The inner HTML string.

      This method operates on innerHTML. The method name is kept short for convenience.

    • Checks if an ARIA attribute exists.

      Parameters

      • name: string

        The ARIA attribute suffix.

      Returns boolean

      true if the attribute exists.

      If name is not a string.

    • Checks if an attribute exists.

      Parameters

      • name: string

        The name of the attribute.

      Returns boolean

      true if the attribute exists, otherwise false.

      If name is not a string.

    • Checks if the Element has a specific class.

      Parameters

      • className: string

        The class to check for.

      Returns boolean

      true if the element has the class.

      If className is not a string.

    • Removes an event listener.

      Parameters

      • eventName: string

        The name of the event.

      • handler: EventListenerOrEventListenerObject | null

        The event handler.

      • Optionaloptions: boolean | EventListenerOptions

        Optional event listener options or boolean.

      Returns this

      This instance for chaining.

      Pass the same handler reference that was used in on() to properly remove the listener.

      const onResize = () => {
      console.log('resized')
      }

      const win = JJET.from(window)
      win.on('resize', onResize)
      win.off('resize', onResize)
    • Adds an event listener.

      Parameters

      • eventName: string

        The name of the event.

      • handler: EventListenerOrEventListenerObject | null

        The event handler.

      • Optionaloptions: AddEventListenerOptions

        Optional event listener options.

      Returns this

      This instance for chaining.

      const onResize = () => {
      console.log('resized')
      }

      JJET.from(window).on('resize', onResize)
      const target = {
      count: 0,
      increment() {
      this.count++
      },
      }

      JJET.from(window).on('click', target.increment.bind(target))
    • Prepends children to this Element.

      Parameters

      • ...children: Wrappable[]

        The children to prepend.

      Returns this

      This instance for chaining.

      el.preChild(JJHE.tree('span', null, 'first'))
      

      To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

    • Maps an array to children and prepends them.

      Type Parameters

      • T

      Parameters

      • array: T[]

        The source array.

      • mapFn: (item: T) => Wrappable

        The mapping function.

      Returns JJE<T>

      This instance for chaining.

      node.preChildMap(['a', 'b'], item => JJHE.create('li').setText(item))
      

      To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      If array is not an array.

      If mapping the array or prepending the children fails.

      • preChild for directly prepending variadic children.
      • preChildren for prepending a pre-built array of children.
    • Prepends an array of children to this Element.

      Parameters

      • children: Wrappable[]

        The children to prepend.

      Returns this

      This instance for chaining.

      This is the array-based companion to preChild. To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      el.preChildren([JJHE.tree('span', null, 'first'), ' child'])
      

      If children is not an array.

    • Replaces a class with another one

      Parameters

      • oldClassName: string

        The class name to remove

      • newClassName: string

        The class name to add

      Returns this

      If the oldClassName doesn't exist, the newClassName isn't added

      If either className is not a string.

    • Removes this node from its parent.

      Returns this

      This instance for chaining.

      If the node has no parent, this method does nothing.

      const doc = JJD.from(document)
      const el = JJHE.create('div')
      doc.body.addChild(el)
      el.rm()
    • Removes one or more ARIA attributes from the Element.

      Parameters

      • ...names: string[]

        The ARIA attribute suffix(es) to remove.

      Returns this

      This instance for chaining.

      el.rmAriaAttr('hidden')  // Remove single
      el.rmAriaAttr('label', 'hidden') // Remove multiple

      If any name is not a string.

    • Removes one or more attributes from the Element.

      Parameters

      • ...names: string[]

        The name(s) of the attribute(s) to remove.

      Returns this

      This instance for chaining.

      el.rmAttr('disabled')  // Remove single
      el.rmAttr('hidden', 'aria-hidden') // Remove multiple

      If any name is not a string.

    • Removes one or more classes from the Element.

      Parameters

      • ...classNames: string[]

        The classes to remove.

      Returns this

      This instance for chaining.

      el.rmClass('active')  // Remove single
      el.rmClass('btn', 'btn-primary') // Remove multiple

      If any class name is not a string.

    • Removes multiple classes from an array of class names.

      Parameters

      • classNames: string[]

        The classes to remove.

      Returns this

      This instance for chaining.

      el.rmClasses(['btn', 'btn-primary'])
      

      If classNames is not an array.

      If any class name in classNames is not a string.

    • Runs a function in the context of this JJET instance.

      Parameters

      • fn: (this: this, context: this) => void

        The synchronous function to run. this inside the function will refer to this JJET instance, and the wrapped instance is also passed as the first argument.

      Returns this

      This instance for chaining.

      node
      .run(function (context) {
      console.log(this.ref)
      console.log(context.ref)
      })
      .trigger(new Event('ready'))

      Use this to make synchronous adjustments while staying in a fluent chain. The callback return value is ignored. If you want to access the current JJ* instance using this, use a function rather than an arrow function.

      • ref for direct access to the wrapped native target.
      • on for event listener chaining.
      • trigger for dispatching events in-chain.
    • Sets a single ARIA attribute on the Element.

      Parameters

      • name: string

        The ARIA attribute suffix.

      • value: unknown

        The value to assign.

      Returns this

      This instance for chaining.

      el.setAriaAttr('hidden', 'true')
      el.setAriaAttr('level', 2)

      If name is not a string.

    • Sets multiple ARIA attributes from an object, or no-ops for nullish input.

      Parameters

      • Optionalattributes: Record<string, unknown> | null

        ARIA attributes object or nullish to skip.

      Returns this

      This instance for chaining.

      This helper is useful for optional ARIA attribute bags in builder APIs.

      • null or undefined: does nothing and returns this
      • plain object: sets each ARIA attribute on the element
      • anything else: throws TypeError
      el.setAriaAttrs({ label: 'Close', hidden: 'false' })
      el.setAriaAttrs(null) // no-op

      If attributes is not nullish and not a plain object.

    • Sets a single attribute on the Element.

      Parameters

      • name: string
      • value: unknown

      Returns this

      el.setAttr('id', 'my-id')
      el.setAttr('x', 50) // Numbers are automatically converted

      If arguments are invalid types.

    • Sets multiple attributes from an object, or no-ops for nullish input.

      Parameters

      • Optionalattributes: Record<string, unknown> | null

        Attributes object or nullish to skip.

      Returns this

      This instance for chaining.

      This helper is useful for optional attribute bags in builder APIs.

      • null or undefined: does nothing and returns this
      • plain object: sets each attribute on the element
      • anything else: throws TypeError
      el.setAttrs({ id: 'app', role: 'main' })
      el.setAttrs(null) // no-op

      If attributes is not nullish and not a plain object.

      setAttr for setting a single attribute.

    • Replaces the existing children of an Element with new children.

      Parameters

      • ...children: Wrappable[]

        The children to replace with.

      Returns this

      This instance for chaining.

      If no children are provided, it empties the Element. To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      el.setChild(JJHE.tree('p', null, 'New Content'))
      
    • Maps an array to children and replaces the existing children with the result.

      Parameters

      Returns JJE<T>

      This instance for chaining.

      This is the mapping companion to setChildren. To make template codes easier, this function ignores mapped nullish children (null and undefined). Other non-node values are coerced into Text nodes. Errors thrown by the mapping function or child replacement are wrapped with a higher-level error that preserves the original cause.

      node.setChildMap(['a', 'b'], item => JJHE.tree('li', null, item))
      

      If array is not an array of Wrappable.

      If mapping the array or replacing the children fails.

      • setChildren for replacing children from a pre-built array.
      • setChild for the variadic replacement form.
      • empty for clearing all children without replacements.
    • Replaces the existing children of an Element with an array of children.

      Parameters

      • children: Wrappable[]

        The children to replace with.

      Returns this

      This instance for chaining.

      This is the array-based companion to setChild. Passing an empty array empties the Element. To make template codes easier, this function ignores nullish children (null and undefined). Other non-node values are coerced into Text nodes.

      el.setChildren([JJHE.tree('p', null, 'New Content')])
      

      If children is not an array of Wrappable.

    • Sets the class attribute.

      Parameters

      • className: string

        The full class attribute value.

      Returns this

      This instance for chaining.

      To remove all classes, pass an empty string: setClass('')

      el.setClass('btn btn-primary')
      el.setClass('')

      If className is not a string.

    • Conditionally adds or removes classes from an object map, or no-ops for nullish input.

      Parameters

      • OptionalclassMap: Record<string, unknown> | null

        Conditional class map or nullish to skip.

      Returns this

      This instance for chaining.

      • null or undefined: does nothing and returns this
      • plain object: truthy values add a class, falsy values remove it
      • anything else: throws TypeError
      el.setClasses({
      active: true,
      disabled: false,
      highlight: isHighlighted,
      })
      el.setClasses(null) // no-op

      If classMap is not nullish and not a plain object.

    • Sets the inner HTML of the Element.

      Parameters

      • html: string | null | undefined

        The HTML string to set, or null/undefined to clear.

      • Optionalunsafe: boolean

        explicit opt-in to set innerHTML. must be true if html is provided.

      Returns this

      This instance for chaining.

      This method operates on innerHTML. The method name is kept short for convenience. Pass an empty string, null, or undefined to clear the content.

    • Attaches a Shadow DOM to the Element if it's not already attached.

      Parameters

      • mode: ShadowRootMode = 'open'

        The encapsulation mode ('open' or 'closed'). Defaults to 'open'.

      • Optionaltemplate:
            | string
            | HTMLElement
            | DocumentFragment
            | HTMLTemplateElement
            | JJDF<DocumentFragment>
            | JJHE<HTMLTemplateElement>
            | JJHE<HTMLElement>

        Optional content to initialize the shadow DOM, which can be a string, DocumentFragment, HTMLTemplateElement, HTMLElement, or any JJ wrapper.

      • ...styles: (string | CSSStyleSheet)[]

        Optional styles to add to the shadow DOM, which can be strings or CSSStyleSheet instances.

      Returns this

      This instance for chaining.

      You can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example <a>).

      If the element cannot have a shadow root, or if arguments are of invalid types.

      If it fails to initialize the shadow DOM with the provided template or styles.

    • Clones and sets template-like input as the only children of this node.

      Parameters

      • template:
            | string
            | HTMLElement
            | DocumentFragment
            | HTMLTemplateElement
            | JJDF<DocumentFragment>
            | JJHE<HTMLTemplateElement>
            | JJHE<HTMLElement>

        The template source to clone and set.

      Returns this

      This instance for chaining.

      Supports HTML strings, native template sources, native Nodes, and any JJ wrapper via JJN. Wrapper inputs are unwrapped and cloned before set.

      el.setTemplate('<p>New Content</p>')
      
      • addTemplate
      • empty for clearing children without adding a replacement template.
    • Shows the Element by removing the hidden and aria-hidden attributes.

      Returns this

      This instance for chaining.

      • hide for the inverse operation.
      • rmAttr for generic attribute removal.
    • Dispatches an Event at the specified EventTarget.

      Parameters

      • event: Event

        The Event object to dispatch.

      Returns this

      This instance for chaining.

    • Creates and dispatches a CustomEvent on the wrapped target.

      Type Parameters

      • T = unknown

      Parameters

      • eventName: string

        The event type name.

      • Optionaldetail: T

        Optional payload exposed as event.detail.

      • Optionaloptions: Omit<CustomEventInit<T>, "detail">

        Additional CustomEvent options excluding detail.

      Returns this

      This instance for chaining.

      This is a convenience wrapper around trigger for the common case of dispatching a payload-bearing custom event.

      The created event defaults to bubbles: true and composed: true. Pass options to override those defaults.

      If eventName is not a string.

      JJET.from(window).triggerCustomEvent('panel-ready', { id: '123' })
      
      JJET.from(this).triggerCustomEvent('todo-toggle', {
      id: '123',
      done: true,
      })
    • Creates a JJE instance from an Element reference.

      Parameters

      • ref: Element

        The Element instance.

      Returns JJE

      A new JJE instance.

      Use this factory method to wrap an existing Element. For creating new Elements, use the specific wrapper type: JJHE.create, JJSE.create, or JJME.create.

      const el = JJE.from(document.querySelector('.my-class'))
      
    • Checks if a value can be passed to the wrap() or unwrap() function.

      Parameters

      • x: unknown

        an unknown value

      Returns x is Wrappable

      true if x is a string, Node (or its descendent), JJN (or its descendent)

      This is useful for filtering the array that is passed to append(), prepend() or setChildren(). See Wrappable type for the full definition.

      • JJN.wrap for converting Wrappable into wrappers.
      • JJN.unwrap for converting Wrappable into native nodes.
    • Extracts the underlying native DOM node from a wrapper.

      Parameters

      Returns Unwrapped

      The underlying DOM node.

      If the input is already a native Node, it is returned as is. If the input is a JJ wrapper, its underlying node is returned. Otherwise, the input is coerced into a Text node. Plain objects are stringified with JSON when possible, and fall back to String(...).

      const rawElement = JJN.unwrap(myJJHE) // Returns HTMLElement
      
    • Unwraps an iterable object (e.g. an array or HTMLCollection).

      Parameters

      • iterable: Iterable<Wrappable>

        The iterable to unwrap.

      Returns Unwrapped[]

      An array of native DOM nodes.

      const nodes = JJN.unwrapAll(wrappedList)
      
    • Wraps a native DOM node or string into the most specific JJ wrapper available.

      Parameters

      • raw: Wrappable

        The object to wrap. If it's already Wrapped, it'll be returned without any change. We don't double-wrap or clone it.

      Returns Wrapped

      The most granular Wrapped subclass instance. If the input is already wrapped, it'll be returned as is without cloning.

      This factory function acts as an intelligent wrapper, inspecting the input type and returning the appropriate subclass of JJN (e.g., JJHE for HTMLElement, JJT for Text, JJSE for SVGElement, etc.). Strings are automatically converted to Text nodes wrapped in JJT.

      If the input is already a JJ wrapper, it is returned unchanged (no double-wrapping). See the full implementation in src/wrappers/JJN.ts which extends this with support for internal wrapper types.

      const bodyWrapper = JJN.wrap(document.body) // Returns JJHE<HTMLBodyElement>
      const textWrapper = JJN.wrap('Hello') // Returns JJT wrapping a new Text node
      const existing = JJN.wrap(alreadyWrapped) // Returns alreadyWrapped unchanged
    • Wraps an iterable object (e.g. an array of wrapped or DOM elements).

      Parameters

      • iterable: Iterable<Wrappable>

        The iterable to wrap.

      Returns Wrapped[]

      An array of wrapped instances.

      const wrappedList = JJN.wrapAll(document.querySelectorAll('div'))