views:

126

answers:

2

I have written a Greasemonkey script which manipulates the contents of certain elements with the following selector:

$("span.relativetime").each(function() { $(this).html("TEST"); });

However, sometimes matching elements are added to the page through AJAX, and I don't know how to handle those new elements. I have tried this, but it doesn't work:

$("span.relativetime").live(function() { $(this).html("TEST"); });

The documentation for jQuery live() says that it wants an event (like "click"). But I don't have any event, I just want to know when something matching my selector has been created, and then I want to modify it.

Background: I am encountering this problem with a Greasemonkey script to display StackOverflow's relative timestamps as absolute local timestamps, which you can find on meta-SO. The problem is when you click "show all comments", the new comments are added by AJAX, and I don't know how to find and replace the timestamps in those scripts.

A: 

With StackOverflow's setup I find it annoying to handle stuff after the comments. What I've done is put a bind on the Add/Remove comments button that uses setTimeout to wait for the elements to be created, and then modify them.

Chacha102
Is there no general-purpose way of doing this though, regardless of what site you're on? It seems like something that would be needed fairly frequently.
Kip
StackOverflow 'creates' the comments. I don't see many sites that do that. They mostly just 'show' them. Instead SO grabs them via AJAX
Chacha102
A: 

One thing you could try (although I'm not sure if it would work) is to cache your selection in some global variable like so:

var $relativetime = $("span.relativetime");

Then you would have your .each function:

$relativetime.each(function() { $(this).html("TEST"); });

After your new elements were added to the DOM, you could reselect append to your cached object:

$relativetime.append("<my html>"); //or
$("<my html>").appendto($relativetime);

(P.s. .html() is for setting html. To set text, use .text()

James Wiseman