2

here if i select some 3 or 4 lines on browser then i want the no of of the selection on browser i.e. count selected <span>

I have an example.html which includes following code then,

<div id="p">
<p id="p1">
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
    <span>wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
</p>
<p>
    <span>wefwef wefwefsdfc fcsdcs wefwscsdc qwefwcsdc </span>
    <span>wefwec acvsdc wecfsdc <br />asdcsdc sdcdc wedwed</span>
    <span> wefwec acvsdc wecfsdc asdcsdc sdcdc</span>
    <span> wefwec acvsdc wecfsdc<br /> asdcsdc sdcdc</span>
</p>
</div>

I have the following questions:

  1. how to count selected <span> ?
  2. how will i get no of selected <span>?
Denim Datta
  • 3,740
  • 3
  • 27
  • 53

1 Answers1

1

You can get the HTML of the selection with a code similar to this one:

function getSelectedHTML () {
    var result = '';
    var range;
    if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        result = range.htmlText;
    }
    else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            range = selection.getRangeAt(0);
            var clonedSelection = range.cloneContents();
            var div = document.createElement('div');
            div.appendChild(clonedSelection);
            result = div.innerHTML;
        }
    }

    return result;
}

After that, it's a matter of parsing the selection. One way would be with jQuery:

var count = $('span', $(getSelectedHTML())).length;
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • 1
    thanks.above code gave result only in case if we select lines of multiple

    tag if we selects lines from single

    tag then it always results to 0 i.e. zero

    – Komal Khatkole Sep 10 '13 at 09:43
  • thank you very much by putting outerHTMl i got expected output – Komal Khatkole Sep 10 '13 at 10:01
  • @KomalKhatkole If you're still having issues, it's probably because the selected HTML isn't fully formed (i.e. you're selecting from the middle of a `span`. You can easily checked this - and add `` in the beginning or `` at the end to make it complete. – Aleks G Sep 10 '13 at 10:30