开发者

How to replace text in a column (inside a table) with Javascript without any ID

The code below shows a rendered HTML (from Compiled ASP .Net code). I would not be able to make any changes to it including adding new attributes like ID.

I could still do something with Javascript but because there is no unique ID for the column, I could not replace the underscore text "____________" with some other text.

The plan is to replace the underscore in column 3 for each row with some other text. Is there a way to identify Column 3 with Javascript?

Thank you.

    <table width='100%'>
        <tr>
            <td align="left" valign="top" class='clsReadOnly'>Row 1
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                abc
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                __________________________
            </td>
        </tr>
        <tr>
            <td align="left" valign="top" class='clsReadOnly'>Row 2
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                def
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                __________________________
            </td>
        </tr>
        <tr>
            <td align="left" valign="top" class='clsReadOnly'>Row 3
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                ghi
            </td>
            <td align="left" valign="top" class='clsReadOnly'>
                __________________________
            </td>
开发者_JAVA百科        </tr>
    </table>


If this is the only table on the page, you can do it with jQuery:

$('table')
    .children('tr')
    .each(function() {
        $(this).children('td:last').html('<p>A Paragraph of Text</p>');
    });


It depends on what you are trying to accomplish. If this is how your table will always look, you could do the following:

var cells = document.getElementsByClassName('clsReadOnly');

cells[2].innerHTML = "Row1 Column3";
cells[5].innerHTML = "Row2 Column3";
cells[8].innerHTML = "Row3 Column3";

If you don't know how many columns you will start with, you would have to do this:

var rows = document.getElementsByTagName('tr');

for (var i=0; i<rows.length; i++) {
    var cells = rows[i].getElementsByTagName('td');

    cells[2].innerHTML = 'Row'+(i+1)+' Column3';
}

jQuery would make this much easier, as you can select by tag, by parent, etc. Of course, you can do all of this in plain JavaScript, but it takes a lot more work.

http://jsfiddle.net/bShZa/


getElementsByClassName() is HTML5 and is not currently supported in IE. Here is the jsfiddle for the solution http://jsfiddle.net/V38MF/2/ w/o jQuery needed

var myTable = document.getElements('td');
for(var i=0; i<myTable.length; i++){
    if((i+1)%3 == 0)
        console.log(myTable[i].innerHTML);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜