PDA

View Full Version : javascript equivalent of document.evaluate?


Rommel
04-29-2007, 06:51 AM
I have this script that works fine in Firefox but now I need it to work in IE and I am having the hardest time trying to make it work, ultra newb I am. It is meant to work on a page like THIS (http://powdod.hlstatsx.com/ingame.php), reading the ID number at the end of a url and adding the specified text if it matches.

The script (barebones, it's long I cut it to two, it is repetitious so if you notice a way to make it more efficient I'm all ears.)

var links
links = document.evaluate('//a[@href]',document,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);
var re_hello = new RegExp("=1$");
var re_doom = new RegExp("=2$");


for (var i = 0; i < links.snapshotLength; i++) {
a = links.snapshotItem(i);
if(a.href.match(re_hello)) {
span = document.createElement('span') ;
a.parentNode.insertBefore(span, a.nextSibling) ;
span.innerHTML = " - Hello World"
}
if(a.href.match(re_doom)) {
span = document.createElement('span') ;
a.parentNode.insertBefore(span, a.nextSibling) ;
span.innerHTML = " - Doom"
}
}

david_kw
04-29-2007, 07:22 AM
If I understand your question, you could do something like this.



var links = document.getElementsByTagName("a");
var objs = [
{ re : /=1$/, text : "- Hello World" },
{ re : /=2$/, text : "- Doom" }
];

for (var i = 0; i < links.length; i++) {
a = links[i];
if (a.href) {
for (var j = 0; j < objs.length; j++) {
if (a.href.match(objs[j].re)) {
span = document.createElement("span");
a.parentNode.insertBefore(span, a.nextSibling) ;
span.innerHTML = objs[j].text;
}
}
}
}


It might actually be faster to use getElementsByTagName instead of xpath unless you have a lot of <a> tags just used as anchors.

Of course I didn't test this so expect some sort of error in my code if you try to implement it.

Hope that helps.

david_kw

Rommel
04-29-2007, 01:15 PM
That looks a lot like what I am already using for another script that modifies the same page this one does. Guess I had the answer right in front of me the whole time. I let frustration get the better of me, it wasn't that great of day yesterday, I was frustrated and distracted with life issues.

Thank you for pointing me back down the right road.

david_kw
04-29-2007, 06:31 PM
Well hopefully things are better for you today. :) Glad to help.

david_kw