I'm using a landing page A/B testing tool called Optimizely. One of the targeting methods is by the URL the visitor is on + a custom Javascript condition. There's a box where I can enter the Javascript condition. I need the condition to search the HTML for the word "checkout" and evaluate to true if found. Any help would be much appreciated. Thanks
Asked
Active
Viewed 503 times
0
-
open the code source (press cmd + u or cmd + option + u on mac) and after use the find press (cmd + f on mac) – GTSouza Jul 15 '12 at 04:29
-
So if the word checkout is anywhere are on the page? Would it be in any of the element "name" attributes, or any other attribute? – James Black Jul 15 '12 at 04:30
-
3If you're using jQuery, you can do `$('body').text().toLowerCase().indexOf('checkout') != -1`. – Blender Jul 15 '12 at 04:32
-
StackOverflow is for programming questions. If you are not a programmer, I'd suggest hiring one or starting to learn with a tutorial. http://www.tizag.com/javascriptT/ – Brad Jul 15 '12 at 04:32
1 Answers
2
I used the treewalker code from this post: getElementsByTagName() equivalent for textNodes
function checkoutIsPresent() {
var result = [];
var root = document.body;
var node = root.childNodes[0];
while (node != null) {
if (node.nodeType == 3) { /* Fixed a bug here. Thanks @theazureshadow */
result.push(node.nodeValue);
}
if (node.hasChildNodes()) {
node = node.firstChild;
}
else {
while (node.nextSibling == null && node != root) {
node = node.parentNode;
}
node = node.nextSibling;
}
}
if (!result) return false;
for (var i = 0, len = result.length; i < len; i++) {
if (result[i].indexOf('checkout') > -1) {
return true;
}
}
return false;
}
If can be called like this:
if(checkoutIsPresent()){
// do something
}
-
I'd convert `result[i]` to lowercase just in case the string is capitalized as well. – Blender Jul 15 '12 at 04:38
-
Yeah, I actually tested with the toLowerCase() in there at first since my test page contained 'Checkout'. Great point. – Perry Tew Jul 15 '12 at 04:42
-
@Blender: myself personally, I like your jQuery solution. I tried to provide a pure javascript just in case it wasn't available, but yours is very elegant (as jQuery often is). – Perry Tew Jul 15 '12 at 04:43
-
1jQuery is *really* nice for things like this. I can't do much without it anymore... – Blender Jul 15 '12 at 04:46