Retaining text selection underneath container element

I’m trying to develop a browser extension that will allow users to select HTML tags on a page using the mouse (like browser inspect mode), but I have problems with implementation. Using scripts, I add the following structure to the page.

<div class="container">
    <div class="item"></div>
</div>
  • container – wrapper for all elements

  • item – element that will add a stroke around the selected element on the page (will be displayed above the main element)

.container {
    position: absolute;
    z-index: 1000000;
}

.item {
    border: 1px solid red;
}
document.addEventListener("mouseover", e => {
    selectElement(e.target);
});
document.addEventListener("mouseout", e => {
    unselectElement(e.target);
});

I tried to implement this functionality via mouseover and mouseout events and ran into a problem. Because of the wrapper on top of the page, I can’t select items on the page. After searching for solutions, I found the following options:

  • add pointer-events: none property to the entire container and content
  • hide the container using visibility: none when moving the mouse, then get the element by coordinates and return the previous visibility state

The first method is not suitable because we have direct access to page events on hover, which can cause tooltips or other windows to appear. This will interfere with the functionality of selecting elements.

The second method is not suitable because of poor performance. If we try to use event mousemove, then when moving the cursor quickly, it will not be able to keep up with the update of item.

Is there any possibility to leave the wrapper and make the selection of elements on the page so that it does not affect performance much?