我有一个包含三列的表,需要访问第三列。我必须检查如果此列中的项目将country作为值,如果是,则添加一个类。
如果没有jQuery,我怎么能这样做?
答案 0 :(得分:0)
<table id="table">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>Poland</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>Germany</td>
</tr>
<tr>
<td>Joe</td>
<td>Jackson</td>
<td>France</td>
</tr>
</table>
在这里,您可以遍历所有行并获得第3列innerHTML以进一步操作
var rowLength = document.getElementById('table').rows.length;
for(var i = 0;i<rowLength;i++){
console.log(document.getElementById('table').rows[i].cells[2].innerHTML);
}
答案 1 :(得分:0)
使用 https://123.1.1.123 ,td:nth-child(3)
作为选择器来抓取每行的第三个单元格。
迭代整个集合,在单元格的 querySelectorAll() 不为空时添加该类:
var cells = document.querySelectorAll('td:nth-child(3)');
for(var i = 0 ; i < cells.length ; i++) {
if(cells[i].textContent.trim() > '') {
cells[i].classList.add('present');
}
}
.present {
background: orange;
}
<table>
<tr><th>First name</th><th>Last name<th>Country
<tr><td>Thomas </td><td>Doe </td><td>Australia</td>
<tr><td>Richard </td><td>Webster </td><td> </td>
<tr><td>Harold </td><td>Hooligan </td><td>USA </td>
</table>
答案 2 :(得分:0)
这是一种有趣的方式,the earlier question & answer
ERROR […] value of type 'AnyObject' has no member 'isKindOfClass'
答案 3 :(得分:0)
HTML
<table id='mytable'>
<tr>
<td class="first">Name</td>
<td class="second">Occupation</td>
<td class="third">Country</td>
</tr>
<tr>
<td class="first">Name</td>
<td class="second">Occupation</td>
<td class="third"></td> <!-- empty -->
</tr>
<tr>
<td class="first">Name2</td>
<td class="second">Occupation2</td>
<td class="third">Country2</td>
</tr>
</table>
的Javascript
var Elements = document.getElementById("mytable").getElementsByClassName("third");
alert(Elements.length);
for (var i=0; i < Elements.length; i++) {
if (Elements[i].textContent != "") {
alert(Elements[i].textContent + " adding class");
Elements[i].className += "new";
}
}
CSS
.new {
background-color: lightblue;
}
使用JSFiddle:https://jsfiddle.net/codeforwin/scyw2by0/