Showing a tooltip on hover based on a tooltip attribute I'm showing a tooltip when you hover an element with the tooltip attribute. E.g. &lt;div class="example" tooltip="Hello World"&gt;Hover me.&lt;/div&gt;

I also have to set the position of the tooltip based on its width, and because I use width: max-content for the element, I have to do something like shown in the code example.

Is there any way I can make my code more efficient? I feel like I'm making it unnecessarily complicated.



(function() {
    var tooltip = document.querySelectorAll("[tooltip]");

    callback = (element, index, array) =&gt; {
        tooltip[index].onmouseenter = () =&gt; {
            let data = element.getAttribute("tooltip");
            let child = document.createElement("div");

            child.className = "tooltip";
            child.innerHTML = data;

            element.appendChild(child);

            child.style.left = "50%";
            child.style.marginLeft = - (child.offsetWidth / 2) + "px";

        }

        tooltip[index].onmouseleave = () =&gt; {
            if(element.getElementsByClassName("tooltip")[0] != undefined) {
                element.removeChild(element.getElementsByClassName("tooltip")[0]);
            }
        }
    }

    tooltip.forEach(callback);
})();
/* Don't review this CSS; it was added just for the demo. */
div[tooltip] { width: max-content; margin: auto; }
&lt;div class="example" tooltip="Hello World"&gt;Hover me.&lt;/div&gt;
Don't do anything in JavaScript that can be done with just CSS!  The :hover pseudo-class is perfect for tooltips.  Use ::after to append a pseudo-element with the tooltip content, where the content is specified by the content property.



div[tooltip]:hover::after {
    content: attr(tooltip);
    display: block;
    position: absolute;
    transform: translateX(-50%);
}

/* Don't review this CSS; it was added just for the demo. */
div[tooltip] { width: max-content; margin: auto; }
&lt;div class="example" tooltip="Hello World"&gt;Hover me.&lt;/div&gt;