简体   繁体   中英

Cant get container of selected text (jsfiddle available)

Lets assume I have some html like this:

  <div id='fooBar' contenteditable='true'>Hello <span class="test">World</span></div>

Javascript Code:

var fooBar = document.getElementById('fooBar');

fooBar.addEventListener('click', function() {
    console.log(window.getSelection().getRangeAt(0).commonAncestorContainer)
});

Question: Why wont It get the actual container named test? I cant figure out why this wont work. I even tried it with selection.anchorNode.parentElement. Nothing works. Now when looking at the internal architecture of the object I get from window.getSelection() then I dont see the span element listed as a property. What am I doing wrong?

https://jsfiddle.net/w7bfmLqd/1/

I've managed to get this working using this:

var fooBar = document.getElementById('fooBar');

fooBar.addEventListener('click', function() {
    console.log(window.getSelection().focusNode.parentElement);
});

https://jsfiddle.net/w7bfmLqd/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM