Search code examples
javascripthtmltampermonkey

Get the name of anchor for selected text


I'm trying to get additional information for the selected text on a webpage, which has following HTML (simplified):

    <h2 class="level2"><span>part 1</span> AAAA<a name="p1"> </a></h2>
    <h3><strong>N1 </strong><a name="NameX"> </a>TitelX</h3>
    <p><a name="N1S1"> </a>(1) Text1.</p>
    <p><a name="N1S2"> </a>(2) Text2.</p>
    <p><a name="N1S3"> </a>(3) Text3.</p>
    <p><a name="N1S4"> </a>(4) Text4.</p>
    ...

What I need, is to get (in Tampermonkey for Chrome) the name on anchor (f.e N1S1), if the user has selected some text (f.e Text1 or part of it).

So far I have got the selected text (after button is pressed):

    $(document).ready(function() {
        $('body').append('<input type="button" value="Button 1" id="b1">')
        $('#b1').css('position', 'fixed').css('bottom', 0).css('left', 0);
        $('#b1').click(function(){
            var x = document.getSelection()
            alert(x)
        });
    });

And I need to find the anchor name for the selection.


Solution

    • Use anchorNode and focusNode to identify where the selection starts/ends (see the Selection documentation)
    • Don't forget to handle the cases of no selection and selection spanning several nodes (like in the comment by @AuxTaco)
    • Once you have the #text node, containing the "(1) Text1."; getting to the anchor name can be as easy as .parentNode.firstElementChild.name - feel free to adapt to your needs.

    function getLinkName() {
      let sel = window.getSelection();
      if (!sel.anchorNode) {
        return "nothing selected";
      }
      if (sel.anchorNode != sel.focusNode) {
        console.log(sel.anchorNode.tagName, sel.focusNode.tagName);
        return "selection spans multiple nodes";
      }
      
      // this will be the <p> element if the text inside it is selected
      let selectionParent = sel.anchorNode.parentNode;
      
      return selectionParent.firstElementChild.name;
    }
    
    function run() {
      alert(getLinkName());
    }
    <h2 class="level2"><span>part 1</span> AAAA<a name="p1"> </a></h2>
        <h3><strong>N1 </strong><a name="NameX"> </a>TitelX</h3>
        <p><a name="N1S1"> </a>(1) Text1.</p>
        <p><a name="N1S2"> </a>(2) Text2.</p>
        <p><a name="N1S3"> </a>(3) Text3.</p>
        <p><a name="N1S4"> </a>(4) Text4.</p>
        
        <button onclick="run()">Check selection</button>