To check if the selected text is within a given CSS class, you can use the getSelection() API in JavaScript to retrieve the selected text and then traverse the DOM to check if any of the selected nodes have the specified CSS class. Here's a step-by-step guide on how to achieve this:

<!-- Sample HTML content --> <div class="container"> <p class="my-text">This is some text.</p> <p>This is another paragraph.</p> </div> <button onclick="checkSelection()">Check Selection</button>
function checkSelection() { const selection = window.getSelection(); const selectedText = selection.toString(); if (selectedText) { const container = document.querySelector('.container'); if (container) { const selectedNodes = getSelectedNodes(container, selection); const hasClass = checkNodesForClass(selectedNodes, 'my-text'); if (hasClass) { console.log('Selected text is within the CSS class "my-text".'); } else { console.log('Selected text is not within the CSS class "my-text".'); } } } } function getSelectedNodes(container, selection) { const range = selection.getRangeAt(0); const selectedNodes = []; const walk = document.createTreeWalker( container, NodeFilter.SHOW_TEXT, (node) => NodeFilter.FILTER_ACCEPT, false ); let node; while ((node = walk.nextNode())) { const nodeRange = document.createRange(); nodeRange.selectNodeContents(node); const intersection = range.intersection(nodeRange); if (intersection && intersection.toString().trim() !== '') { selectedNodes.push(node); } } return selectedNodes; } function checkNodesForClass(nodes, cssClass) { for (const node of nodes) { let parent = node.parentElement; while (parent) { if (parent.classList.contains(cssClass)) { return true; } parent = parent.parentElement; } } return false; }

In this example, we have a simple HTML content with a button to trigger the check and a container with some text inside it. When you select some text within the container and click the button, it will check if the selected text is within the CSS class "my-text".

The checkSelection() function is triggered when the button is clicked. It first gets the selected text using window.getSelection(). Then, it finds the container element with the class "container" using document.querySelector(). Next, it calls the getSelectedNodes() function to get an array of text nodes that intersect with the selection.

The getSelectedNodes() function uses a tree walker to traverse the DOM and find the text nodes that intersect with the selection.

Finally, the checkNodesForClass() function checks if any of the selected nodes or their ancestors have the specified CSS class. If any of the nodes or their ancestors have the class, it returns true, indicating that the selected text is within the given CSS class.

Note that this example assumes that the text selection does not span across multiple non-text elements (e.g., <div>, <span>, etc.). For more complex scenarios, you may need to further enhance the selection logic.

Have questions or queries?
Get in Touch