0

I would like to be able to look in the first span within a div with a class of t_links and buy and detect if the string Account appears. If it does then I want to set some tracking code in jQuery/JavaScript.

There will always be one span within this div. How can I search the contents for an instance of Account using jQuery?

<div class="t_links buy">
  <span><a class="" href="https://www.ayrshireminis.com/account/login/">Account</a></span>
</div>
crmpicco
  • 16,605
  • 26
  • 134
  • 210

3 Answers3

3

:contains is what you're looking for:

$(".t_links.buy span:first:contains('Account')")

http://api.jquery.com/contains-selector/

Edit: Added first as @adeneo pointed out. This will ensure that it's the first span that you're looking at.

jholloman
  • 1,959
  • 14
  • 16
1

Try (See Demo)

​$(document).ready(function () {
    if($('.t_links.buy span').text().indexOf('Account')) {
        // code
    }
});​

Or

​$(document).ready(function () {
    if($(".t_links.buy span:contains('Account')").length) {
        // code
    }
});​
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Using html() will only operate on the first result of the selector if there are multiple. If this is the intended solution then .text() would be more efficient, it would strip out the tags which are not needed for evaluation. – jholloman Jul 30 '12 at 14:28
1

Span has exact match :

if ($("span:first", ".t_links.buy")​.filter(function() {
    return $(this).text() === 'Account';
})​.length) {
    //set tracking code
}

Span contains :

if ($("span:first", ".t_links.buy")​.filter(function() {
    return $(this).text().toLowerCase().indexOf('account') != -1;
})​.length) {
    //set tracking code
}

If there is only one span, you can drop the :first.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Good point with :first, I missed that requirement in the question. The :contains selector will eliminate the need for a custom filter though unless there is a performance gain I'm unaware of. – jholloman Jul 30 '12 at 14:37
  • I would probably have gone for an answer with `:contains` as well, but I noticed there already was an answer, so decided to use a `filter()`. Does'nt really matter in most cases, the performance gain either way will not be noticeable. – adeneo Jul 30 '12 at 14:39