1

I have this function:

$containing = jQuery('#test a').filter(function(){
    return jQuery(this).text().substring(0,2) == "Ba";
});

if ($containing.length > 0) {
    $containing.first().addClass('testtt');
}

This adds the class to the first anchor it finds, but that's not what I want. I wanted to give the class to all the anchors containing Ba... I tried replacing first with each, but nothing happened at all. Can someone help me out?

user1770896
  • 159
  • 1
  • 1
  • 11

2 Answers2

3

Just remove .first(), then it will be applied to all the objects in the jQuery array, not just the first.

$containing = jQuery('#test a').filter(function(){
    return jQuery(this).text().substring(0,2) == "Ba";
});

if ($containing.length > 0) {
    $containing.addClass('testtt');
}
Sergio
  • 28,539
  • 11
  • 85
  • 132
2

Just remove .first(). Chaining in jQuery allows most functions to be applied to all of the selected elements.

$containing = jQuery('#test a').filter(function(){
    return jQuery(this).text().substring(0,2) == "Ba";
});

if ($containing.length > 0) {
    $containing.addClass('testtt');
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189