Pompey
Pompey

Reputation: 606

Get the width of an existing td element

I have a table that is created dynamically with jQuery and it has a number of columns. I don't know what is going to be in the table, or how many columns there will be. Depending on what is inside of the td, each td will have a different width. What I want to do is to get the width of the td and use it for later.

This is what my table can look like. https://i.sstatic.net/gV3v6.jpg

As you can see it has different sized columns. So I just want to go and get the width of each element. This is my code:

var topTds = $("#ResultSetTable tr:first");
topTds = topTds.children();
console.log(topTds);
//for each of the tds we want to go and get their scrollwidth
for(var m = 0; m < topTds.length; m++){
    console.log(topTds[m], "client: ", topTds[m].clientWidth, "offset ", topTds[m].offsetWidth, "scroll ", topTds[m].scrollWidth);
}

As you can see I've tried all the different width things I can think of, but they aren't printing out the right number. This is the result that I am getting https://i.sstatic.net/XrkkR.jpg

However when I scroll over using chrome I get different numbers, and it the chrome numbers are the correct ones. This is what chrome shows https://i.sstatic.net/6Yx3m.jpg

So basically I have no idea what I am doing wrong. Any help would be really appreciated!

Upvotes: 0

Views: 748

Answers (1)

Pietro Saccardi
Pietro Saccardi

Reputation: 2622

As you're using jQuery, you can take advantage of the width() method provided.

for(var m = 0; m < topTds.length; m++) {
    console.log(topTds[m], "jQuery width: ", topTds.eq(m).width());
}

clientWidth, offsetWidth and scrollWidth represent different quantities, and computing the final width of a HTML element can be quite tricky because of CSS properties and box model. Besides, you should check when console.log is called, if all the CSS and JavaScript was loaded, and the table filled with data: these can be the reasons for the strange values you get.

In my experience, jQuery's width() never failed in computing the actual width of an object.

Some reference:

Upvotes: 1

Related Questions