Search code examples
javascripttypescriptdomdom-manipulation

insertAdjacentElement is not adding or appending the element in the target element


I created a function to create div

function createDivElement(className: string): HTMLDivElement {
    const divElement = document.createElement('div')
    divElement.className = className

    return divElement
}

after that I created another function which returns elements or structure of Tooltip I am making

function generateTooltip() {
    const TooltipParent = createDivElement(`tooltip-parent-${randomString(8)}`)
    const Tooltip = createDivElement(`tooltip-${randomString(8)}`)
    const TooltipArrow = createDivElement(`tooltip-arrow-${randomString(8)}`)
    const TooltipContent = createDivElement(`tooltip-content-${randomString(8)}`)

    return { TooltipParent, Tooltip, TooltipArrow, TooltipContent }
}

and Finally I made a function that creates tooltip

const Tooltip = function (props: Props) {
    'use strict'
    
    // rest of the code
    generateTooltip().Tooltip.insertAdjacentElement('afterbegin', generateTooltip().TooltipArrow)
    generateTooltip().Tooltip.insertAdjacentElement('beforeend', generateTooltip().TooltipContent)
    generateTooltip().TooltipParent.insertAdjacentElement('afterbegin', generateTooltip().Tooltip)
     
    // appending on the body
    document.body.appendChild(generateTooltip().TooltipParent)
}

Now in DOM the last line of the function i.e appending .tooltip-parent div on the body is working rest of the code isn't working which means the elements above this line is not appending in the target element.

As you can see only the element which I am appending on body is rendering in the DOM

FOR REFERENCE OR IDEA


Solution

  • Every time you call generateTooltip() you generate a new set of elements. For example, calling generateTooltip().TooltipParent twice will give you two different TooltipParent divs. So no element is referenced and appended correctly.

    The solution lies in calling generateTooltip() only once, and use all the elements from that single call to build your structure.

    const TooltipElement = function (props: Props) {
      const { 
        TooltipParent, 
        Tooltip, 
        TooltipArrow, 
        TooltipContent 
      } = generateTooltip();
    
      Tooltip.append(TooltipArrow, TooltipContent);
      TooltipParent.append(Tooltip);
      document.body.append(TooltipParent);
    }
    

    I rename Tooltip to TooltipElement to avoid duplicate names, as you already have Tooltip element inside the function.

    You can still use insertAdjacentElement instead of append, but I didn't see a real advantage of use the former over the latter.