[英]Fetch all first child elements from a table
很简单,我需要获取所有第一种元素th的文本:
<html>
<body>
<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>Line #1</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Line #2</td>
<td>SLD</td>
<td>68</td>
</tr>
<tr>
<td>Line #3</td>
<td>MDK</td>
<td>68</td>
</tr>
</table>
<script type="text/javascript">
console.log(document.querySelectorAll('table tr td:first-of-type'));
</script>
</body>
</html>
我希望能够获取所有表tr td:first-of-type innertext ...这里需要进行一些小的调整。
我以某种方式解决了它...跟踪和错误...谢谢:)
<html>
<body>
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td>Line #1</td>
<td>MKD</td>
<td>68</td>
</tr>
<tr>
<td>Line #2</td>
<td>SLD</td>
<td>32</td>
</tr>
<tr>
<td>Line #3</td>
<td>HAD</td>
<td>53</td>
</tr>
<tr>
<td>Line #4</td>
<td>LRD</td>
<td>49</td>
</tr>
</table>
<script type="text/javascript">
var theFirstChilds = document.querySelectorAll('table tr td:first-of-type');
var i;
for (i = 0; i < theFirstChilds.length; ++i) {
console.log(theFirstChilds[i].innerText);
}
</script>
</body>
</html>
我想这就是你的意思
document.querySelectorAll('table tr td:first-child')
表tr td:第一个孩子
正如Dan Philip所提到的,您需要像下面那样调整HTML。
<table>
<tr>
<td>Line #1</td>
<td>Lastname</td>
<td>Age</td>
</tr>
<tr>
<td>Line #2</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Line #3</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
这是一个使用jquery的Codepen.io示例(仅用于说明):
https://codepen.io/wykydtronik/pen/yMGMYw
$( "table tr td:first-child" )
.css( "text-decoration", "underline" )
.hover(function() {
$( this ).addClass( "gogreen" );
}, function() {
$( this ).removeClass( "gogreen" );
});
var theFirstChilds = document.querySelectorAll('table tr td:first-child');
console.log(theFirstChilds[0]);
console.log(theFirstChilds[1]);
console.log(theFirstChilds[2]);
请注意,jQuery只是您要尝试执行的操作的示例。 在codepen上,您可以打开底部的控制台,以查看从节点存储的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.