3

I have a function that gets the selected text of a content, but what I want to do is to get this selected text and also add a unique id to its html tag.

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
 $('#outline').on('click',function(){
       var text = getSelectedText();
//here want to add the unique id to this paragraph that contains this text
});

I am stuck and can't find something similar elsewhere.

1 Answers1

0

Here's an example of what you are looking to do.

Demo: https://jsfiddle.net/xo01kxLa/1/

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}
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;
}
$('#outline').on('click', function () {
    var text = getSelectedText();
    var parent = getSelectionParentElement();
    $(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
});

If you only want the unique ID to be set once, then make it:

$('#outline').on('click', function () {
    var text = getSelectedText();
    var parent = getSelectionParentElement();
    if($(parent).attd('id') != '') {
            $(parent).attr('id', 'id' + Math.floor((Math.random() * 1000) + 1));
    }
});
Sators
  • 2,746
  • 1
  • 20
  • 26