Monica
Monica

Reputation: 1534

"unrecognized expression: [object Object]" when using $(..)

I have the following code:

 $(".budget-channel-table").each(function() {

        //get table
        var table = $(this);

        //create an array to hold the auto calculated widths of each element
        var thWidthsArr = [];
        var calcWidth = 0;
        $(table + " th").each(function() {
            calcWidth = $(this).css("width");
            thWidthsArr.push(calcWidth);
        });
 });

And I don't understand why I keep getting this error in my console:

Uncaught Error: Syntax error, unrecognized expression: [object Object] th 

Upvotes: 0

Views: 2844

Answers (6)

Neel
Neel

Reputation: 11741

Write your code in .find as shown below:

table.find("th").each(function() {
          calcWidth = $(this).css("width");
          thWidthsArr.push(calcWidth);
     });

For more information:
http://api.jquery.com/find/

Upvotes: 0

SSA
SSA

Reputation: 5493

It's because table is already a jquery element. change it to this

table.find("th")......

$(".budget-channel-table").each(function() {

        //get table
        var table = $(this);

        //create an array to hold the auto calculated widths of each element
        var thWidthsArr = [];
        var calcWidth = 0;
        table.find("th").each(function() {
            calcWidth = $(this).css("width");
            thWidthsArr.push(calcWidth);
        });
 });

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

Use .find() to get the children of objects

$(table).find("th").each(function() {
    calcWidth = $(this).css("width");
    thWidthsArr.push(calcWidth);
});

Upvotes: 1

GillesC
GillesC

Reputation: 10874

table is a jquery object here is how you can use directly as a context to search into. Also you could simply use this if you don't need table later.

$("th", table)

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You need to use find(). table is a jQuery object so when you use it in a string concatenation it creates selector like [object Object] th which is a invalid selector thus the error.

   table.find("th").each(function() {
        calcWidth = $(this).css("width");
        thWidthsArr.push(calcWidth);
    });

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85633

Replace this line:

$(table + " th").each(function() {

With this:

$("th", this).each(function() {

Or use find method:

$(table).find('th').each(function() {

Upvotes: 1

Related Questions