views:

36

answers:

1

I have an html page that is generated by a CMS. I cannot modify the page, but can add JavaScript.

Each time the page loads, a JavaScript function (that I cannot modify) dynamically inserts a paragraph onto the page.

How can I use JQuery to .remove() that paragraph whenever it is loaded?

For example, when the page first loads, it look like this (blank):

<div></div>

Then, a few seconds later, a JavaScript function (that I have no control over) adds a paragraph to the page. The page then looks like this:

<div><p id="foo">bar</p></div>

How can I use JQuery to remove the paragraph with id=foo each time it is dynamically loaded onto the page?

+2  A: 

You can use the liveQuery plugin for this:

$("#foo").livequery(function() {
  $(this).remove();
});
Nick Craver
it would be better with `$("p#foo")`+1 anyways :)
Sarfraz
@Sarfraz - I assume since it's being added, it has a very specific ID that the OP knows, no need to qualify that with a tagname...that actually slows the selector down if it's a sufficiently unique ID, if it's something generic and not cross-page unique then by all means, slap a tagname on there.
Nick Craver
@Nick Craver: hmm agreed only OP knows that specifically and yes you have to do it in a generic fashion.
Sarfraz
For performance reasons, you shouldnt prefix id selectors with the tag (unlike classes).
James Westgate
On the subject of livequery, its not that great from a performance pov, and am now trying to get it removed from the website Im working on. On the other hand, its very useful for dom manipulation. It may be better and try hook the ajax or something that loads the paragraph.
James Westgate
@James - The question specifically states this about the load of that element: "that I have no control over". As for the ID selectors, a `ul#menu` has a different meaning than `div#menu`, and in a shared script you may want to run a different function for each...there are valid cases to have a tagname prefix.
Nick Craver