¿Cómo puedo obtener el elemento en el que se encuentra el texto resaltado?

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.

Por ejemplo:

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

The bookmarklet code:


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.


preguntado el 09 de enero de 11 a las 00:01

Not to be an obscene spammer or anything, but I recently wrote a bookmarklet generator that throws jQuery on the page and allows you to write your bookmarklet in an external script. I don't mind if you examine the code being executed ya sea. -

3 Respuestas

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


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)


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

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

Respondido 22 Oct 19, 12:10

Great idea, however anchorNode is not supported on IE :-/ - Koes Bong

ie9 does support it (msdn.microsoft.com/en-us/library/ff974688%28VS.85%29.aspx), the others microsoft browsers offers a non standard (do you can believe it?) solution. - Eineki

This approach is generally correct. See my answer for the same approach fully fleshed out. - Tim Down

I had no idea about anchorNode +1 for that - qwertymk

Sé consciente de anchorNode is not necessarily a text node (it could be an element), so using its parentNode property is not always going to work. - Tim Down

You can do this relatively simply in all major browsers. Code is below, live example: http://jsfiddle.net/timdown/Q9VZT/

function getSelectionTextAndContainerElement() {
    var text = "", containerElement = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var node = sel.getRangeAt(0).commonAncestorContainer;
            containerElement = node.nodeType == 1 ? node : node.parentNode;
            text = sel.toString();
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        containerElement = textRange.parentElement();
        text = textRange.text;
    return {
        text: text,
        containerElement: containerElement

Respondido el 09 de enero de 11 a las 04:01

I don't think you can, he only way to know which element is currently being used would be to use a onclick event on the element. Other than that there is no sure way. You can however search each element until you find an element with the same text,

jQuery('*:contains(' + selected + ').

You can add an event to get the current element with this code though (untested)

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e){
        window.selectedElement = all[i];
        //preventDefault $ StopBubble &
        return false;

And it will be stored in selectedElement

Ok try This:

var all = document.getElementsByTagName('*');
for (var i = 0; i < all.length; i++)
    all[i].onclick = function(e) {
        window.selectedElement = this;
        ((e && e.stopPropagation && e.stopPropagation()) ||
         (window.event && (window.event.cancelBubble = true)));
        return false;

DEMO: http://jsfiddle.net/HQC6Z/1/ Mejor todavía: http://jsfiddle.net/HQC6Z/

After looking at the other answers, I take back my solution and offer theirs:

¿Cómo puedo obtener el elemento en el que se encuentra el texto resaltado?

¿Cómo puedo obtener el elemento en el que se encuentra el texto resaltado?

contestado el 23 de mayo de 17 a las 15:05

Thanks. I don't think the first option of searching each element is feasible - especially with jQuery - since not all sites with have jQuery. So trying to do this with just pure JS. I tried the second solution and no luck. alerting (selectedElement) returns nothing. :-/ - Koes Bong

Thanks for the fiddle. But pardon my ignorance, but how exactly do I test that? I ran it and click on the list items and nothing happened. - Koes Bong

Try the second link, it's on jsFiddle which uses iframes so you can't really test it on their site, but you can see how to implement it based on the alert box, or try jsfiddle.net/HQC6Z/3 with firebug - qwertymk

Got the second link to work. So clicking on the list items show the innerHTML, but how do I show what element it's in, or is that not possible as you mentioned? - Koes Bong

This is brutal and highly inefficient, will break existing click event handlers, and won't work for selections selected via keyboard. You can get the selection text and the element containing the selection without needing any of this. See my answer. - Tim Down

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.