Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the DOM element which contains the current selection?

You can select a part of a web page with the mouse.

I know that I can get the currently selected text but how can I get the DOM element which contains the start or end of the current selection?

like image 950
Aaron Digulla Avatar asked Aug 26 '09 14:08

Aaron Digulla


People also ask

How do I find my DOM element?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What does DOM element contain?

The DOM is the way Javascript sees its containing pages' data. It is an object that includes how the HTML/XHTML/XML is formatted, as well as the browser state. A DOM element is something like a DIV, HTML, BODY element on a page. You can add classes to all of these using CSS, or interact with them using JS.

How do you access DOM elements in node JS?

Simply, you cannot. There is no DOM on the server, just a plain html source file. The "DOM" is the "Document Object Model", which is an in-memory representation of the HTML elements that were parsed by the browser. Node isn't a browser and so there is no DOM API available.


1 Answers

The following will return the container element of the start or end boundary of the current selection, using the boolean isStart to specify whether you want the start or end boundary. It will work in most mainstream browsers. Add feature tests for more robustness.

function getSelectionBoundaryElement(isStart) {     var range, sel, container;     if (document.selection) {         range = document.selection.createRange();         range.collapse(isStart);         return range.parentElement();     } else {         sel = window.getSelection();         if (sel.getRangeAt) {             if (sel.rangeCount > 0) {                 range = sel.getRangeAt(0);             }         } else {             // Old WebKit             range = document.createRange();             range.setStart(sel.anchorNode, sel.anchorOffset);             range.setEnd(sel.focusNode, sel.focusOffset);              // Handle the case when the selection was selected backwards (from the end to the start in the document)             if (range.collapsed !== sel.isCollapsed) {                 range.setStart(sel.focusNode, sel.focusOffset);                 range.setEnd(sel.anchorNode, sel.anchorOffset);             }        }          if (range) {            container = range[isStart ? "startContainer" : "endContainer"];             // Check if the container is a text node and return its parent if so            return container.nodeType === 3 ? container.parentNode : container;         }        } } 
like image 67
Tim Down Avatar answered Sep 25 '22 18:09

Tim Down