0

How can it be that this doesn't alert 0 (instead, it alerts 50)?

I need the td position relative to the table

http://jsfiddle.net/vxVCE/

HTML:

<div style="height:40px"></div>
<div>
    <table id="tbl">
        <tr>
            <td id="td1">linje 1</td>
        </tr>
        <tr>
            <td id="td2">linje 2</td>
        </tr>
    </table>
</div>

JS:

var elm = $('#td1');
var position = elm.position();
alert(position.top);

edit: I need the tr position relative to the table :)

4 Answers 4

3

Add position: relative; to the table. Doing that will make it alert 0. Otherwise, it's finding position relative to the document.

1

Because it is not at the top -- therefore it is not zero


The body has a padding of 10px.
The div above the table is 40px in height.

Therefore it alerts "50" (10 + 40 = 50)

1

@Neal has explained beautifully why it gives 50. Here's the second part:

To get the position w.r.t the to table, subtract table's top from the td top:

alert(position.top - $('#td1').closest('table').position().top);

Demo: http://jsfiddle.net/mrchief/vxVCE/1/

Note: Depending on your HTML/CSS, you might have to use table's offset instead.

alert(position.top - $('#td1').closest('table').offset().top);
2
  • that seems complicated for no reason. also it does not explain why it alerts 50 in the OP's example.
    – Naftali
    Aug 16, 2011 at 18:38
  • @Neal: It may be complicated (arguably though), but it is what you need if you want to get the td position relative to table's viewport. And you already explained nicely why it gives 50, din't wanna repeat the same.
    – Mrchief
    Aug 16, 2011 at 18:41
0

Just to add the position relative to the table you will also need to add it to the tbody if you have one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.