0

how can i change the inner html by getting element by index
i want to change the content of cells according to their index values

<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
function LFLS() {
    // LFLS => load from local Storage
    for (i = 0; i < localStorage.length; i++) {
        key = localStorage.key(i);//it return values like ("1,2","2,5", etc.)
        console.log(key)
        row = key.split(",")[0];
        col = key.split(",")[1];
//how to get the cell by row and col
}
}
1
  • Have a look this may help you, jQuery eq() Commented Aug 29, 2022 at 4:51

3 Answers 3

2

As Sakil said you can use eq(). Try this:

function LFLS() {
    // load from local Storage
    for (i = 0; i < localStorage.length; i++) {
        key = localStorage.key(i);
        row = key.split(",")[0];
        col = key.split(",")[1];
        // how to get the cell by row and col
        $("table tr").eq(row).children().eq(col).html('NEW VALUE')
    }
}

Sign up to request clarification or add additional context in comments.

Comments

0

I believe you need the following snippets.

Before your for loop

const rows = $("table tr");

After you obtain row & col variables

const cellToUpdate = rows[row].children[col];

Alternatively, if you're looking to programatically loop through the table you could use the following snippet.

<script type="text/javascript">

    const rows = $("table tr");
    for( i = 0; i < rows.length; i++ ) {
        const currRow = rows[i];
        const rowChildren = currRow.children;
        for( n = 0; n < rowChildren.length; n++ ) {
            const cell = rowChildren[n];
            cell.innerHTML = "My new data for row: " + i + " in cell " + n;
        }
    }
</script>

1 Comment

bro its overly confusing + the solution above is better and simple
0

Is something on the lines of below not going to work for you for some reason?

$("table tr:nth-of-type([your-row])).eq([your-col]).html([your_content]);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.