buti-oxa
buti-oxa

Reputation: 11431

How to get selection HTML and selection parent?

Several of years ago, I added "smart quoting" to a web forum. Basically, user selects a part in previous conversation and clicks a button to quote it. Script gets the HTML of the quote and goes up the DOM tree to figure out who said that.

I could only do it for IE, although I remember trying hard. But then, there was no stackoverflow.com and Firefox was not as mature. I guess that by now, doing it in Firefox is as easy. Here's the key part of the code.

range2Copy = frameDoc.selection.createRange(); 
html2Copy = range2Copy.htmlText; 

el = range2Copy.parentElement();

// go up the HTML tree until post row node (id=postrowNNNN)

while (el.nodeName != 'BODY' &&
        !el.id.match(/postrow/)) {

    el = el.parentNode;
}

Element frameDoc contains the previous thread where user selects text. If it makes too little sense, see the whole code here. It is a plugin for FCKeditor.

Upvotes: 3

Views: 7163

Answers (1)

Nadia Alramli
Nadia Alramli

Reputation: 114933

OK, I tried to run your code in firefox and it didn't work, this is the modified version that worked:

var selection = window.getSelection(); 
var node = selection.anchorNode;

while (node.nodeName != 'BODY' && !node.id.match(/postrow/)){
    node = node.parentNode;
}

Upvotes: 6

Related Questions