tags:

views:

46

answers:

4

I’m having a problem trying to detect if a table exists using jQuery. The table has no class or ID.

What I’m trying to achieve is to not have the following code fire unless a table exists:

function tableAltRows()
    {
        $("#content table tr:even").each(function(){
            $(this).addClass("alt");
        });
    }
$(tableAltRows);

So I changed the last line to:

if ($('table').length > 0) {
    $(tableAltRows);
}

But the line checking the table length never returns anything other than 0. As a test, if I change it to == 0 it calls the tableAltRows function. I’m not that familiar with jQuery, so I assume I’m missing something obvious?

+1  A: 

I suspect that you're not calling your function when the DOM is ready. Try:

$(document).ready(function() {
    if($('table').length) {
        alert('hello');
    }
});
karim79
A: 

This seems to work for me:

<html>

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
    $(document).ready(function() {
        alert($('table').length);
    });
</script>
</head>

<body>
<table></table>
<table></table>
</body>

</html>
Gerald Kaszuba
A: 

If you are calling the element before it exists, it will not work.

You can:

  1. Insert the script after the element
  2. Make the script execute when the page is ready

See this example

BrunoLM
A: 

Firstly. Holy crap! I can’t get over how quick my question was answered.

@BrunoLM: The table is being generated by CFML code in our CMS. One of the pages having a problem is the search page (which will be fixed in another few minutes thanks to everyone who has replied). I don’t have an example page as it’s on a development server behind our firewall.

@Felix Kling: The code was in the bottom of the header.

@Everyone: Wrapping the check with $(document).ready(function() {}); has fixed the problem (thank you).

tHeSmUrF