Greasemonkey: insert an element using regular expression

A

Alexander Paul

Hi!

I'm a newbie to JavaScript and Greasemonkey and just started learning
with 'Dive Into Greasemonkey'. I looked for an example on the web, but
unfortunately I'm still missing something...

I have a text file which is a simple database:

Key01 Text01 Url01
Key02 Text02 Url02
....

I'd like to insert after

<a href="anUrl" class="thisClass">Key01<a>

the element

<a href="Url01">Text01<a>

I tried to reuse the "Dumb Quotes" from 'Dive Into Greasemonkey' by
replacing

replacement = {
"Key01":"Key01</a><a href=\"Url01\">Text01",
"Key02":"Key02</a><a href=\"Url01\">Text02"
};

Unfortunately, this doesn't work, since </a><a href...> is not
interpreted as a HTML tag.

So I tried this:

nodes = document.evaluate(
"//text()",
document,
null,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
null);
for (var i = 0; i < nodes.snapshotLength; i++) {
node = nodes.snapshotItem(i);
text = node.data;
for (key in replacements) {
if(s==key)
helpkey=key;
}
newLink = document.createElement('a');
// newLink.href = 'Url0x'; ????
// newLink.appendChild(document.createTextNode(Text0x)); ???
newLink.parentNode.insertBefore(newLink, node.nextSibling);
}

I'm really lost. :(

I would be most grateful for any help or ideas...

Alex
 
U

User1014

* Alexander Paul said:
Hi!

I'm a newbie to JavaScript and Greasemonkey and just started learning
with 'Dive Into Greasemonkey'. I looked for an example on the web, but
unfortunately I'm still missing something...

I have a text file which is a simple database:

Key01 Text01 Url01
Key02 Text02 Url02
...

(snip)

Looks like a job for XSLT to me.
 
M

Martin Honnen

Alexander said:
I have a text file which is a simple database:

Key01 Text01 Url01
Key02 Text02 Url02
...

I'd like to insert after

<a href="anUrl" class="thisClass">Key01<a>

the element

<a href="Url01">Text01<a>

You can use XPath to find the first link e.g.
var link = document.evaluate(
'.//a[@href][. = "Key01"]',
document.body,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE
null
).singleNodeValue;
Then you can create the new link and insert it:
if (link != null) {
var newLink = document.createElement('a');
newLink.href = 'Url01';
newLink.appendChild(document.createTextNode('Text01'));
link.parentNode.insertBefore(newLink, link.nextSibling);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top