简体   繁体   中英

Replacing the content of a <td> with <tr> id and <tr> index

I have a table structure like this

<table>
    <tr id="tr_1">
        <td>Content1</td>
        <td>Content2</td>
        <td>Content3</td>
        <td>Content4</td>
    </tr>
    <tr id="tr_2">
        <td>Content5</td>
        <td>Content6</td>
        <td>Content7</td>
        <td>Content8</td>
    </tr>
    <tr id="tr_1">
        <td>Content11</td>
        <td>Content12</td>
        <td>Content13</td>
        <td>Content14</td>
    </tr>
    <tr id="tr_2">
        <td>Content15</td>
        <td>Content16</td>
        <td>Content17</td>
        <td>Content18</td>
    </tr>
</table>

I am passing the row index(2) and <tr> id (tr_1) to a js function for replacing the content of 2nd 3 rd td's in that row. i have a jquery funcion

document.getElementById('tr_1').getElementsByTagName("td")[2].innerHTML = '<td>New html</td>';

But that this replacing the first tr html. How we can replace with id tr_1 with index 2

Try this:

jQuery("[id=tr_1]:eq(1) td:eq(1)").html("new html");

Note you need to insert the jquery plugin:

http://jquery.com/download/

if you are using jquery .. then this should work..

$("#tr_1 td").eq(2).html("<td>New html</td>");

here is the link to eq()... http://api.jquery.com/eq/

Try this

<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
    $('#tr_1 td:eq(1)').html('Replacing Content of td 2');
    $('#tr_1 td:eq(2)').html('Replacing Content of td 3');
});                
</script>

You don't have unique ids. Is is essential for JavaScript that the DOM working with unique ids.

In jQuery you can use this to target the to tr elements with id set to tr_1 :

$("tr[id=tr_1]");

To get the second element in these tr's you will need to use jQuery.fn.each

$("tr[id=tr_1]").each(function() {
    $("td", this).eq(1).html("new html");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM