1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

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");
    });
})
Community
  • 1
  • 1
Andrew Mao
  • 35,740
  • 23
  • 143
  • 224
  • The way that you're doing it is somewhat convoluted, but here's how it would work: http://jsfiddle.net/qqm9a/3/ – Andrew Mao Feb 25 '13 at 22:18
  • I changed my question to not use `div`s at all, and the code is in JSFiddle, try it. It works for your span, div, whatever. – Andrew Mao Feb 25 '13 at 22:35
-1

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.

Ionel Lupu
  • 2,695
  • 6
  • 29
  • 53