How to pick up paragraphs from a selected text snippet?

Asked

Viewed 58 times

1

Imagine that the snippet between keys is a text selected with the mouse...

That I captured with:

window.getSelection().toString();

<p> <--- [pegar daqui]
Meu texto selecionado {está aqui
</p>
<p>
E aqui} também
</p> <--- [até aqui]

How could I extract the paragraphs from an HTML picking start and end of paragraphs where a selection took place?

I tried this, but it doesn’t capture what actually exists, it just makes a copy of the paragraph type containers into a container:

function containerSelection(sel) {
     if (sel.rangeCount) {
        var container = document.createElement('div');
            container.setAttribute('id', 'check_selection');
            container.setAttribute('style', 'display:none');

           for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
           }

          document.body.appendChild(container); 
     }
}

I mean, instead of the method taking this:

<div id="check_selection">
 <p>Meu texto selecionado {está aqui
    </p>
    <p>
    E aqui} também
    </p>
</div>

He’s getting it like this:

<div id="check_selection">
 <p>{está aqui</p>
 <p>E aqui}</p>
</div>

I know this attribute catches the father, but it’s taking the container from where the paragraphs are: range.commonAncestorContainer

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.