Othuna
Othuna

Reputation: 129

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 highlighted text so that I can (for example) hide them:

$("Highlighted text").hide();

What is the highlighted text selector, and how to hide highlighted text?

Upvotes: 2

Views: 1413

Answers (2)

Manwal
Manwal

Reputation: 23816

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:

function getSelectionParentElement() {
    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;
            }
        }
    } else if ( (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);
        }
    } else if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0).cloneRange();
            if (range.getClientRects) {
                range.collapse(true);
            }
        }
    }
    return range.startOffset;
}

Updated DEMO

Upvotes: 3

user3459464
user3459464

Reputation: 224

 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

Upvotes: 0

Related Questions