user1526459
user1526459

Reputation: 1

Javascript Condition to Search HTML for String and Return True

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

Upvotes: 0

Views: 555

Answers (1)

Perry Tew
Perry Tew

Reputation: 2632

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
}

Upvotes: 2

Related Questions