Reputation: 25
I am trying to write a Greasemonkey script that will take a web page that has a series of un-ID'ed linked images and replace them with bolded text.
The path I was taking has unfortunately lead to a couple of dead ends.
First, the code I have for some reason replaces the image with the [CLICK] text, and then immediately runs through the parent/replace again and erases the [CLICK].
Second, I now have the sneaking suspicion that there's no good way to bold that createTextNode.
So could someone #1 explain why that loop wasn't working for me, and #2 tell me the right way to do this so that I can have the added text be bold.
var smiliesList = document.evaluate(
"//img[contains(@src,'smilies')]", document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var prefixReplace = document.createTextNode('[CLICK]');
var prefixImgSrc = ('smilies/goofyimage.png')
for (var i=0;i<smiliesList.snapshotLength;i++) {
var node = smiliesList.snapshotItem(i);
if (node.src == prefixImgSrc) {
node.parentNode.replaceChild(prefixReplace, node);
}}
Upvotes: 1
Views: 2990
Reputation: 1933
I believe you need to create a new replacement text node for each image while you're in the loop. You're currently only creating a single node prior to the loop.
Also, to create bold text, just create a <b>
element and then use innerHTML
to put text inside.
var smiliesList = document.evaluate(
"//img[contains(@src,'smilies')]", document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var len = smiliesList.snapshotLength;
for (var i=0; i<len; i++) {
var node = smiliesList.snapshotItem(i),
p;
if (node.src.indexOf('smilies/goofyimage.png') > -1) {
var textNode = document.createElement('b');
textNode.innerHTML = '[CLICK]';
if (node.parentNode) {
p = node.parentNode;
p.removeChild(node);
p.appendChild(textNode);
}
}
}
Also, I couldn't help but think there may be a better way of doing this. I'd recommend going with this version - fewer lines of code and more browser compatibility:
var imgs = document.getElementsByTagName('img');
for (var i = imgs.length - 1; i >= 0; i--) {
if (imgs[i].src.indexOf('smilies/goofyimage.png') > -1) {
var textNode = document.createElement('b');
textNode.innerHTML = '[CLICK]';
imgs[i].parentNode.replaceChild(textNode, imgs[i]);
}
}
Upvotes: 1
Reputation: 93443
Here's how easy the whole script is with jQuery:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
// smilies/goofyimage.png is case-sensitive
var goofyImages = $("img[src*='smilies/goofyimage.png']");
goofyImages.replaceWith ("<b>[CLICK]</b>");
This uses:
Upvotes: 0