How to save where in the DOM of a webpage the html element is

  dom, firefox, firefox-webextensions, html, javascript

I am making a highlighting browser plugin for firefox as a project.

I am trying to find a way to save where in a webpage a user highlights so I can reproduce it on reload.

I do my highlighting by getting what text the user has selected with their mouse, and surrounding that text with a span (and putting a background color for that span).

But what is an efficient way to save where the user highlighted.

I see two ways:

  1. traverse the dom from the highlight/span until reach an element with an ID. Then save this path.
  2. Perform a find.find() using the firefox javascript API (, and then "Using rectData" (ctrl+f "Using rectData" the document I linked to see what I mean. "picture speaks a thousand words") use this to know which selection I highlighted. For example: I highlight "the red cat", and it appears 3 times throughout the document, but I highlighted the 2nd one. Using "rectData" I could find this 2nd "the red cat" on a revisit to the same webpage and re-highlight it.

But, these seem quite brute force, and I have a suspicion that there must be an easier way.

Is there a better way to do this?

Source: Ask Javascript Questions