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?
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.
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.
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.
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; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With