开发者

how can I get the position of a cell in a table using javascript?

By position I mean, how many columns are to the left of the cell and how many rows are on top of it. What I need exactly is two functions:

function FindColPos(element)
{
/* find column position */
return colPos;
}

function FindRowP开发者_C百科os(element)
{
/* find row position */
return rowPos;
}

the functions MUST be written that way, I can't add other stuff to my document like ID's since I only have access to the head of the document where I would insert the javascript functions. (All this is part of another project in C#). The element passed to the function would be a cell in a row (a <TD> element) but it would be better if I can pass any element inside the <TD> and the function can recognize the parent <TD>. I'm not advanced enough on javascript to figure it out myself. I actually don't even know if it's possible. Hope you can help.


I don't know if every browser supports it but there exist TableCell objects, which have a cellIndex property and TableRow objects that have a rowIndex property.

So it would be:

function FindColPos(element)
{
    return element.cellIndex;
}

function FindRowPos(element)
{
    return element.parentNode.rowIndex;
}

assuming element is a td object.

But I have not find information yet which browser supports it. The newest Safari does ;)

Update:

Those properties are even supported in IE 5.5, FF 1.0, Safari 1.0 and Opera 7.0. So I'd say it is pretty save to use them and much faster than iterating over all the preceding elements.

You might also be interested in sectionRowIndex which gives the index relative to the elments tbody, thead or tfoot. rowIndex returns the index relative to the whole table.


you should be able to iterate back over previous nodes at the same level, and count the appropriate nodes until you run out.

something like

function FindColPos(element) {
    /* find column position */

    var colPos = 0;
    var prev = element.previousSibling;

    while (prev) {
        if (prev.nodeType == 1 && prev.nodeName.match(/t[dh]/i)) {
            colPos++;
        }
        prev = prev.previousSibling;
    }

    return colPos;
}

function FindRowPos(element) {
    /* find row position */

    var rowPos = 0;
    var prev = element.parentNode.previousSibling;

    while (prev) {
        if (prev.nodeType == 1 && prev.nodeName.match(/tr/i)) {
            rowPos++;
        }
        prev = prev.previousSibling;
    }

    return rowPos;
}

colPos and rowPos would be the index if all the elements of the same type were considered as a zero-based array.

edit: just for clarity, both cells are assumed to take a cell as the element.

edit2: this method counts merged cells as one. you can look for the colspan attribute on an element if you need to count a merged cell as pieces rather than a whole.

edit3: FindRowPos was off by 1, fixed now.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜