完全替换HTML表格中的cel

时间:2017-08-29 14:24:09

标签: javascript html

我有这样的事情:

<table id="myTable">
    <tr>
       <td class="1">cell 1</td>
       <td class="2">cell 2</td>
    </tr>
    <tr>
       <td class="3">cell 3</td>
       <!-- from here -->
       <td class="4">cell 4</td>
       <!-- to here -->
    </tr>
</table>

我需要的是在JavaScript中替换单元格4中的所有代码,我的意思是替换

<td class="4">cell 4</td>

<td id="8" class="3" title="important">cell 4</td>

我试过了:

var cell = document.getElementById("myTable").rows[1].cells;
cell[1] = newCode;

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
function myFunction() {
    var h1 = document.getElementsByClassName("4")[0];
    var atttittle = document.createAttribute("tittle");
    atttittle.value = "important";
    h1.setAttributeNode(atttittle);
    var attid = document.createAttribute("id");
    attid.value = "8";
    h1.setAttributeNode(attid);
    var attclass = document.createAttribute("class");
    attclass.value = "3";
    h1.setAttributeNode(attclass);
    var element=document.getElementById("8");
        alert(element.outerHTML);
}
&#13;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="myTable">
    <tr>
       <td class="1">cell 1</td>
       <td class="2">cell 2</td>
    </tr>
    <tr>
       <td class="3">cell 3</td>
       <td class="4">cell 4</td>
    </tr>
</table>
<button onclick="myFunction()">Click here replace </button>
</body>
</html>
&#13;
&#13;
&#13;

对不起以前的回答。我改为JavaScript

答案 1 :(得分:-1)

你可以使用JQuery。像这样:http://api.jquery.com/replacewith/

希望有所帮助

编辑:

在您的示例中,您可以使用以下内容:

$( ".4" ).replaceWith( "<td id="8" class="3" tittle="important">cell 4</td>" );
相关问题