简体   繁体   中英

How do I get the element containing clicked text in Javascript/Jquery?

I would like to replace the text on pages when I click on the text or even just replace the single word clicked on. I have tried a top down approach selecting all elements in the DOM, filtering out the textNodes, wrapping each with tags and adding a click event handler to each tag. But this is far too slow and inefficient particularly on very large and dynamic sites.

I only need to replace the text that was clicked. Is there a bottom up way of doing this starting from the event.target? How do I find the closest textNode to the event.target, for example?

In the example you gave, you can just do the following; for more info see How do I select text nodes with jQuery?

$(document).click(function(event) {     
    textNodes = $(event.target).contents().filter(function() {
        return this.nodeType == 3;
    });

    textNodes.each( function() {
         $(this).replaceWith("New Text");
    });
})

Have you tried Jquery's .closest() ?

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM