Skip to content Skip to sidebar Skip to footer

Jquery Selector For Highlighted Text

I want to know how to select Highlighted text using JQuery selector. For example, to select elements with a class, you use .class, for IDs, you use #id. What do I use for highligh

Solution 1:

This is one your are looking for i believe:

text = window.getSelection().toString();

DEMO

Hide selected/highlighted text javascript

You have to get parent of Element from DOM:

functiongetSelectionParentElement() {
    var parentEl = null, sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            parentEl = sel.getRangeAt(0).commonAncestorContainer;
            if (parentEl.nodeType != 1) {
                parentEl = parentEl.parentNode;
            }
        }
    } elseif ( (sel = document.selection) && sel.type != "Control") {
        parentEl = sel.createRange().parentElement();
    }
    return parentEl;
}

NEW DEMO

Update

Fixed demo to hide text we have to find startOffset

function getStartOffset() {
    var sel = document.selection, range, rect;
    var x = 0, y = 0;
    if (sel) {
        if (sel.type != "Control") {
            range = sel.createRange();
            range.collapse(true);
        }
    } elseif (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0).cloneRange();
            if (range.getClientRects) {
                range.collapse(true);
            }
        }
    }
    returnrange.startOffset;
}

Updated DEMO

Solution 2:

if($("idDiv").html().contains('Highlighted text')==true)
 {
   var a=$("#idDiv").html();
   a=a.replace("Highlighted text","<p id='highlightedtext'>Highlighted text</p>");
   $("#idDiv").html(a);
   $("#highlightedtext").hide();
  }

The above code check the highlighted text from the div and if it found it set that text in p tag with id and using that id you can hide it

Post a Comment for "Jquery Selector For Highlighted Text"