Newbie - Injecting HTML around existing elements?

2,808 views
Skip to first unread message

Ross

unread,
Jan 31, 2008, 8:38:50 AM1/31/08
to greasemonkey-users
Hi, I'm fairly new to Greasemonkey, but have been playing with it
after picking up the basics from Dive into Greasemonkey and looking at
various user scripts.

DiG explains how to inject some content before/after a given element,
including complex HTML. Is there a way to add HTML using Greasemonkey
so the injected tag begins before an element, but only closes after
the element?

For example, let's say I've got a simple page:

BODY
Heading
IMG
IMG
Text area
/BODY


- Is it possible to add a <div> field that is inserted before the
second IMG tag but doesn't end until after the text block (making the
following:)

...
IMG
<div [my specified content here]>
IMG
Text area
</div>
/BODY


I'm not sure if I am going to have to replace part of the page to get
the wrapper HTML around the items I want, or if there's another way.
Any guidance you can provide would be greatly appreciated!

-Ross

Matt Sargent

unread,
Jan 31, 2008, 11:17:21 AM1/31/08
to greasemon...@googlegroups.com
Just add the DIV as you already know how, then set the elements you want inside it to be child nodes of the DIV.

RodMcguire

unread,
Jan 31, 2008, 11:20:58 AM1/31/08
to greasemonkey-users
It sounds like you are thinking of scripts as something that
manipulate the HTML text string of a page as opposed to where they
really work which is on the DOM structure that the page is parsed
into.

Lets (for simplicity sake) assume all your nodes have "id"s such that.

hN = document.getElementById('head');
i1N = document.getElementById('img1');
i2N = document.getElementById('img2');

If you want to wrap a div around the two <img> nodes then would do
something like:

myDiv = document.createElement('div');
myDiv.appendChild(i1N);
myDiv.appendCHild(i2N);
hN.parentNode.insertBefore(myDiv, hN.nextSibling);

You don't have to remove the <img> nodes from the body because because
by the logic of DOM manipulation they can only appear in one place.

To instead put i2N and everything that follows into myDiv you just
need to loop through those elements and .appendChild to myDiv, though
you need to be careful how you loop through them because you are
moving them and things like .nextSibling will change after a node is
moved.


http://developer.mozilla.org/en/docs/DOM:element

Ross

unread,
Jan 31, 2008, 1:11:15 PM1/31/08
to greasemonkey-users
Thank you - I think I'm finally getting an idea of how scripts are
really supposed to be used.

Thanks for the example, too - I'm going to play with this for a while
but I think you've given me everything I need to get through this!

-Ross
Reply all
Reply to author
Forward
0 new messages