鉴于此表:
<table border="1" width="200" id="table1" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="#CB2F7F">
<tr id="st_ppp">
<td width="60%" class="totalLabels">Price per piece</td>
<td width="39%" align="right" class="totalElements">unknown</td>
</tr>
<tr id="st_qty">
<td width="60%" class="totalLabels">Quantity</td>
<td width="39%" align="right" class="totalElements">unknown</td>
</tr>
<tr>
<td width="60%"> </td>
<td width="39%" align="right"> </td>
</tr>
<tr>
<td width="60%" class="subTotalLabel">Sub-Total:</td>
<td width="39%" align="right" class="subTotal">unknown</td>
</tr>
</table>
我想做类似以下伪代码的事情:
document.getElementById("st_ppp").[td whose class is totalElements].innerHTML="NewPrice";
document.getElementById("st_qty").[td whose class is totalElements].innerHTML="NewQty";
我也对HTML的任何其他更改提出建议,这些更改将使JS更易于使用。
答案 0 :(得分:3)
只需使用querySelector
(MDN link)和相应的CSS选择器即可获取您的元素并更改其内容。
document.querySelector( '#st_ppp .totalElements' ).innerHTML = "NewPrice";
document.querySelector( '#st_qty .totalElements' ).innerHTML = "NewQty";
答案 1 :(得分:2)
如果您不担心与Internet Explorer 7及更早版本的兼容性,querySelector
非常适合(但如果您这样做,请转而使用@Sirko):
document.querySelector('#st_ppp > .totalElements').innerHTML = "NewPrice";
如果你已经在使用jQuery,那就非常好了:
$('#st_ppp > .totalElements').text('NewPrice');
否则,循环将起作用:
var pricePerPiece = document.getElementById('st_ppp');
var i, c;
for(i = 0; c = pricePerPiece.children[i]; i++) {
if((' ' + c.className + ' ').indexOf(' totalElements ') > -1) {
c.innerHTML = 'NewPrice';
break;
}
}