最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get selection HTML and selection parent? - Stack Overflow

programmeradmin3浏览0评论

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 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.

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. 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.

Share Improve this question asked May 10, 2009 at 16:07 buti-oxabuti-oxa 11.4k5 gold badges36 silver badges44 bronze badges 1
  • It seems you already have a working code. I don't understand the problem you have – Nadia Alramli Commented May 10, 2009 at 16:15
Add a ment  | 

1 Answer 1

Reset to default 6

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;
}
发布评论

评论列表(0)

  1. 暂无评论