jj
    Preparing search index...

    Class JJDF<T>

    Wraps a DocumentFragment (which is a descendant of Node).

    DocumentFragments are lightweight versions of Document that store a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the active document tree structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made.

    const doc = JJD.from(document)
    const frag = JJDF.create()
    frag.addChild(
    JJHE.tree('div', null, 'Item 1'),
    JJHE.tree('div', null, 'Item 2'),
    )
    doc.body.addChild(frag)

    Type Parameters

    • T extends DocumentFragment = DocumentFragment

    Hierarchy (View Summary)

    Index

    Constructors

    • Creates an instance of JJDF.

      Type Parameters

      • T extends DocumentFragment = DocumentFragment

      Parameters

      • ref: T

        The DocumentFragment instance to wrap.

      Returns JJDF<T>

      If ref is not a DocumentFragment.

    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.

    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 JJDF<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.

    • 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 JJDF<T>

      A new wrapped instance of the clone.

    • Removes all children from this Element.

      Returns this

      This instance for chaining.

      el.empty()
      
    • 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.

    • 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 JJDF<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.

    • 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()
    • 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.
    • 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 JJDF<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.

    • 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.
    • 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 JJDF instance from a DocumentFragment reference.

      Parameters

      • ref: DocumentFragment

        The DocumentFragment instance.

      Returns JJDF

      A new JJDF instance.

      Use JJDF.create to create a new empty DocumentFragment. For other Node types, use JJN.from or the specific wrapper type.

      const frag = JJDF.from(myFrag)
      
    • 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'))