开发者

How do I detect if a table exists (which doesn't have a class or ID)

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 ass开发者_StackOverflow社区ume I’m missing something obvious?


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜