5

I'm writing a script for CasperJS. I need to click on the link that contains a span with "1". In jQuery can be used :contains('1'), but what the solution is for selectors in pure Javascript?

HTML: <a class="swchItem"><span>1</span></a><a class="swchItem"><span>2</span></a>

jQuery variant: $('a .swchItem span:contains("1")')

UPD CasperJS code:

casper.then(function () {
    this.click('a .swchItem *select span with 1*')
})

4 Answers 4

7

Since 0.6.8, CasperJS offers XPath support, so you can write something like this:

var x = require('casper').selectXPath;

casper.then(function() {
    this.click(x('//span[text()="1"]'))
})

Hope this helps.

1

Try the following. The difference between mine and gillesc's answer is I'm only getting a tags with the classname you specified, so if you have more a tags on the page without that class, you could have unexpected results with his answer. Here's mine:

var aTags = document.getElementsByTagName("a");
var matchingTag;

for (var i = 0; i < aTags.length; i++) {

    if (aTags[i].className == "swchItem") {
        for (var j = 0; j < aTags[i].childNodes.length; j++) {
            if (aTags[i].childNodes[j].innerHTML == "1") {
                matchingTag = aTags[i].childNodes[j];
            }
        }
    }
}
1
var spans = document.getElementsByTagName('span'),
    len = spans.length,
    i = 0,
    res = [];

for (; i < len; i++) {
    if (spans.innerHTML == 1) res.push(spans[i]);
}

Is what you have to do unless the browser support native css queries.

1

jQuery is javascript. There are also a number of selector engines available as alternatives.

If you want to do it from scratch, you can use querySelectorAll and then look for appropriate content (assuming the content selector isn't implemented) and if that's not available, implement your own.

That would mean getting elements by tag name, filtering on the class, then looking for internal spans with matching content, so:

// Some helper functions
function hasClass(el, className) {
  var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
  return re.test(el.className);
}

function toArray(o) {
  var a = [];
  for (var i=0, iLen=o.length; i<iLen; i++) {
    a[i] = o[i];
  }
  return a;
}

// Main function
function getEls() {

    var result = [], node, nodes;

    // Collect spans inside A elements with class swchItem
    // Test for qsA support
    if (document.querySelectorAll) {
      nodes = document.querySelectorAll('a.swchItem span');

    // Otherwise...
    } else {

      var as = document.getElementsByTagName('a');
      nodes = [];

      for (var i=0, iLen=as.length; i<iLen; i++) {
        a  = as[i];

        if (hasClass(a, 'swchItem')) {
          nodes = nodes.concat(toArray(a.getElementsByTagName('span')));
        }
      }
    }

    // Filter spans on content
    for (var j=0, jLen=nodes.length; j<jLen; j++) {
      node = nodes[j];

      if ((node.textContent || node.innerHTML).match('1')) {
        result.push(node);
      } 
    }
    return result;
}
2
  • The :contains() pseudo-class is no longer part of the CSS standard, and as such is not recognized by querySelectorAll(). That said, you can indeed refer to the source code to see how jQuery/Sizzle implements :contains() using JS.
    – BoltClock
    Commented Apr 13, 2012 at 13:09
  • I've spent a bit of time wading through jQuery, I don't really want to see how it does :contains. It should be doing it like I am—matching on the textContent or innerText (whichever is supported), though it may use it's own text function (which is unnecessary and slower, but I don't know if that's what it actually does).
    – RobG
    Commented Apr 13, 2012 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.