The reason you are seeing your HTML appended to multiple items is most likely because of the existence of iframes in the markup you are dealing with.
Each iFrame (an I suspect that the gadgets, ads are iFrames) have their own entire HTML structure complete with <html></html>
and <body></body>
tags. When you .appendTo('body')
, your script will append the content to any element that matches the 'body'
selector.
You'll want to give a more unique selector than $('body')
.
What you might want to do is try using $('body:first')
of some sort of other unique selector in addition to the generic body
selector. You might have to play with this a bit because you are depending on HTML that is not in your control - I assume you'd like your GM script to run on any page - so you are limited to the structure of that page. There is no guarantee for example, that the :first
<body>
tag will be the correct one.
If you ask me, the one sure fire way to do this would be to iterate over all of the <body>
elements that $('body')
returns and for each one see if it has a parent element that is an Iframe.
Something like this -
var selectedElement = '';
$('body').each(function(index,elem){
if ($(elem).closest('iframe').length){
selectedElement = $(elem);
}
});
if (selectedElement){
// appendTo(selectedElement);
}
I'm using the .each()
function to iterate over all the elements that match the given selector - in this case - body
.
I'm using the .closest()
function here to navigate through all of the parent elements and find the ancestor that matches the given selector - in this case - iframe
.