Advertisement
YaBoiSwayZ

highlight selected elements within docs

Aug 10th, 2023
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.89 KB | Source Code | 0 0
  1. // Get the user selection
  2. const selection = window.getSelection();
  3.  
  4. // Get the array of selected elements
  5. const selectedElements = getSelectedElements(document);
  6.  
  7. // Add a class to each selected element
  8. selectedElements.forEach(element => element.classList.add("highlighted"));
  9.  
  10. // Define the getSelectedElements function using TreeWalker
  11. function getSelectedElements(doc) {
  12.   const selectedElements = [];
  13.   const selection = doc.defaultView.getSelection();
  14.   let nodeRange = doc.createRange();
  15.  
  16.   // Hack for browsers without getRangeAt
  17.   if (!selection.getRangeAt) {
  18.     selection.getRangeAt = i => {
  19.       const range = doc.createRange();
  20.       if (i || !selection.anchorNode) return range;
  21.       range.setStart(selection.anchorNode, selection.anchorOffset);
  22.       range.setEnd(selection.focusNode, selection.focusOffset);
  23.       return range;
  24.     };
  25.     selection.rangeCount = 1;
  26.   }
  27.  
  28.   for (let i = 0; i < selection.rangeCount; ++i) {
  29.     const selectedRange = selection.getRangeAt(i);
  30.     const containerNode = selectedRange.commonAncestorContainer;
  31.  
  32.     // Create a TreeWalker object with the container node as the root
  33.     const treeWalker = doc.createTreeWalker(
  34.       containerNode,
  35.       NodeFilter.SHOW_ELEMENT,
  36.       node => NodeFilter.FILTER_ACCEPT,
  37.       false
  38.     );
  39.  
  40.     // Loop through the nodes in the TreeWalker and check if they are in the selected range
  41.     let node;
  42.     while ((node = treeWalker.nextNode())) {
  43.       nodeRange.selectNodeContents(node);
  44.       if (
  45.         nodeRange.compareBoundaryPoints(selectedRange.END_TO_START, selectedRange) < 1 &&
  46.         nodeRange.compareBoundaryPoints(selectedRange.START_TO_END, selectedRange) > -1
  47.       ) {
  48.         selectedElements.push(node);
  49.       }
  50.     }
  51.   }
  52.  
  53.   // Detach the node range to avoid memory leaks
  54.   nodeRange.detach();
  55.  
  56.   // Return the array of selected elements
  57.   return selectedElements;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement