Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your problem is that selections work slightly differently between browsers when one or both of the selection boundaries coincide with DOM node boundaries. For example, if the user selected the word "bar" in page content with the following HTML</p> <pre><code>&lt;p&gt;foo&lt;i&gt;bar&lt;/i&gt;&lt;/p&gt; </code></pre> <p>... there are four different possible locations for the selection start that all look visually identical to the user:</p> <ol> <li>At the end of the "foo" text node (node "foo", offset 3)</li> <li>After one child node of the <code>&lt;p&gt;</code> element (node <code>&lt;p&gt;</code>, offset 1)</li> <li>After zero children of the <code>&lt;i&gt;</code> element (node <code>&lt;i&gt;</code>, offset 0)</li> <li>At character index 0 of the "bar" text node (node "bar", offset 0)</li> </ol> <p>Most browsers do not allow all these positions in practice, but unfortunately different browsers make different choices. In Firefox, the selection you've made selects the whole <code>&lt;span&gt;</code> element and the selection range's <code>startContainer</code> is the <code>&lt;span&gt;</code>'s parent node. You could detect this by examining the range to see if it selects a single node:</p> <pre><code>function rangeSelectsSingleNode(range) { var startNode = range.startContainer; return startNode === range.endContainer &amp;&amp; startNode.hasChildNodes() &amp;&amp; range.endOffset === range.startOffset + 1; } </code></pre> <p>You can use this to detect what kind of selection you have and obtain the selected element accordingly:</p> <pre><code>var selectedElement = null; if (rangeSelectsSingleNode(range)) { // Selection encompasses a single element selectedElement = range.startContainer.childNodes[range.startOffset]; } else if (range.startContainer.nodeType === 3) { // Selection range starts inside a text node, so get its parent selectedElement = range.startContainer.parentNode; } else { // Selection starts inside an element selectedElement = range.startContainer; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload