2

How to get the span name of selected text:

 <Span class='class1'> text2 text3 text4 text5 </span> text6

when user select text4 then I want to get Span=Class1

Any answer can help ( in Jquery or Rangy or ...)

ouss88
  • 35
  • 5

3 Answers3

3

This is a function which may help:

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;
}

It was taken from here Get parent element of a selected text, Author: Tim Down

Community
  • 1
  • 1
Liglo App
  • 3,719
  • 4
  • 30
  • 54
1
$('span').on('click', function(){
var classes = $(this).attr('class');
console.log(classes)   //if there are more than one class do classes.split(' ')
})

Extremely unedited fiddle https://jsfiddle.net/tvp0q761/

Amit
  • 427
  • 4
  • 16
0

Here's a vanilla JS way of doing it. It assumes you'll have more than one span, hence querySelectorAll rather than querySelector.

HTML

<span class="class1"><p>text2</p><p>text3</p><p>text4</p></span>
<span class="class2"><p>text2</p><p>text3</p><p>text4</p></span>
<span class="class3"><p>text2</p><p>text3</p><p>text4</p></span>

JS

var spans = [].slice.call(document.querySelectorAll('span')).forEach(function (el) {
    el.onclick = showParentInfo;
});

function showParentInfo() {
    console.log(this.nodeName + '=' + this.className)   
}

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • it works well but I am using a button to print with alert the class of selected word with rangy. How should I proceed – ouss88 Jun 24 '15 at 11:57
  • I don't know anything about rangy, I'm afraid. I did change my code so that it will alert the class of the text when you doubleclick on it (select it). [Does this help?](http://jsfiddle.net/eovtrp8z/14/) – Andy Jun 24 '15 at 13:27