Asperger
Asperger

Reputation: 3222

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/

Upvotes: 0

Views: 47

Answers (1)

Matt
Matt

Reputation: 4117

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/

Upvotes: 1

Related Questions