views:

41

answers:

1

Hey all, I've been trying to get a series of objects to appear that have multiple classes associated with them

<div class="Foo Bar">
    Content
</div>

<script>
    alert($('.Foo').length);
</script>

The selector above is returning 0. This is unfortunately one of those questions that is completely impossible to ask to google (at least as far as I can tell).

How can I make this query work?

To be more specific, I have a table that looks like this:

<table>
    <tr class="Location2">
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
    </tr>
    <tr class="Location3 Territory4">
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
        <td>Data</td>
    </tr>
</table>

When I script:

alert($('.' + (Var that = 'Territory4')).length));

I get 0.

I'm well versed in HTML and CSS and I know I shouldn't use tables etc etc, but this is a special case.

+2  A: 

EDIT: Based on updated question.

Your code throws a syntax error. Bring the variable assignment out of the selector.

var that = 'Territory4';

alert( $('.' + that).length );

The selector is correct. I'm guessing that your code is running before the DOM is fully loaded.

Try this: http://jsfiddle.net/QWNPc/

$(function() {
    alert($('.Foo').length);
});

Doing:

$(function() {
    // your code
});

is equivalent to doing:

$(document).ready(function() {
    // your code
});

which ensures that the DOM has loaded before the code runs.

http://api.jquery.com/ready/

patrick dw
The code is a click event that doesn't seem to be working. It comes right after a rather large method call that creates a table, but the table is fully loaded when I click.
C Bauer
@C Bauer - So the `click` event doesn't fire? Or it returns the wrong result? You'll have to show your code to see what the issue is. The code you posted works as long as the selected element is in the DOM.
patrick dw
That's kind of the problem, there's a lot of code creating that table. I pared everything down to make it simpler...
C Bauer
@C Bauer - Trouble is that you pared out the issue. :o) Is the `.Foo` element (or whatever it actually is) part of the table? And again, are you saying that the `click` handler doesn't fire at all? Or that it fires, but gives the wrong result? Or are you triggering a click after the `table` is done. There are so many possibilities for what your code could be doing.
patrick dw
I've edited the original question in order to show the issue properly. Thanks for your patience.
C Bauer
@C Bauer - You've got a syntax error. You'll need to bring the variable assignment out of the selector. I'll update my answer.
patrick dw
Turns out it was a sneaky space after the variable text 'Territory4 ' that I couldn't see because of the alert box :X
C Bauer