Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - How can I get the element in which highlighted text is in?

I am trying to learn how to write a bookmarklet where I can highlight some text, click on the bookmarklet and have it tell me what got highlighted. I can get that far, but next I want to know what element that text is in.

For example:

<div id="some-id">to be highlighted</div>

The bookmarklet code:

javascript:(function(){alert(window.getSelection();})()

If I highlight the text "to be highlighted" and then click on the bookmarklet, it will alert the text. But how can I get the element in which the text is in, in this case the element after that?

So the flow is: highlight text, click bookmarklet, bookmarklet tells you what you highlighted and the element it's in.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something similar to this to get the dom element that contains the selected text.

window.getSelection().anchorNode.parentNode

It works on firefox and Chrome, you should test it into the remaining browsers.

It have a quirk, if you select text that beholds to more than an element, only the first one is returned. But maybe you can live with this.

Just for reference on what is the anchorNode property: http://help.dottoro.com/ljkstboe.php

On internet explorer this snippet should do the trick (I can't test it)

document.selection.createRange().parentElement();

as stated into http://msdn.microsoft.com/en-us/library/ms535872.aspx and http://msdn.microsoft.com/en-us/library/ms536654.aspx

A range explanation on quirksmode: http://www.quirksmode.org/dom/range_intro.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...