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

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

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

function FindRowPos(element)
{
/* find row position */
return rowPos;
}

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

+3
2

, .

-

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 rowPos , .

edit: .

edit2: . colspan , , .

edit3: FindRowPos 1, .

+2

, , TableCell , a cellIndex TableRow rowIndex.

, :

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

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

, element td.

, . Safari ;)

Update:

IE 5.5, FF 1.0, Safari 1.0 Opera 7.0. , , .

sectionRowIndex, tbody, thead tfoot. rowIndex .

+4

Source: https://habr.com/ru/post/1757901/


All Articles