Reputation: 13
I'd like to do a Greentext plugin for Firefox using Greasemonkey,but without jQuery.
Here's what I did:
<head>
<script type="text/javascript">
function highlight() {
var elm = document.getElementsByClassName("mainWrapper");
for(i = 0; i < elm.length; i++)
{
elm[i].innerHTML.replace(">","pony");
}
}
alert("PONY");
</script>
</head>
<body onload="highlight()">
<div class="mainWrapper"><span class="noob"> > N00b </span>
</div>
</body>
This is a testing version for the function, I did it because I think that the problem was Greasemonkey, but it doesn't work yet.
Can you help me? I'm not very good at programming and I don't know how to script on JS very well.
Upvotes: 1
Views: 258
Reputation: 93493
For something like this, you need to work on only the text parts of the page -- so that the HTML (and any attached JS) is not wrecked.
So (1) do not use innerHTML
, and (2) The code would best use a technique called recursion, to efficiently parse the nodes.
Also note that > can be coded as either >
or >
(and possibly some rarer methods too).
Here is a complete Greasemonkey script that does this kind of search and replace:
// ==UserScript==
// @name _Replace HTML-sensitive text
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @include http://fiddle.jshell.net/DJLEq/*
// @grant none
// ==/UserScript==
var targElements = document.querySelectorAll ("div.mainWrapper");
for (var J = targElements.length - 1; J >= 0; --J) {
repGreaterWithPonies (targElements[J] );
}
function repGreaterWithPonies (node) {
if (node.nodeType === Node.TEXT_NODE) {
// YOUR CUSTOM REPLACE GOES HERE.
node.nodeValue = node.nodeValue.replace (/>|>/ig, "pony");
}
else if (node.nodeType === Node.ELEMENT_NODE) {
for (var K = 0, numNodes = node.childNodes.length; K < numNodes; ++K) {
repGreaterWithPonies (node.childNodes[K] );
}
}
}
Install that script and you can see it work on this page: fiddle.jshell.net/DJLEq/...
Upvotes: 2
Reputation: 29549
Not exactly clear on the question, but looking at your code it looks like you would like to do something like:
<head>
<script type="text/javascript">
function highlight() {
var elm = document.getElementsByClassName("mainWrapper");
for(i = 0; i < elm.length; i++)
{
elm[i].innerText = elm[i].innerText.replace(">","pony");
}
}
</script>
</head>
<body onload="highlight()">
<div class="mainWrapper">><span class="noob"> N00b </span>
</div>
</body>
Upvotes: 0