[英]How to get nested js selectors like td?
I need to get all selector that match the condition so I can iterate thru it later on.我需要获取与条件匹配的所有选择器,以便以后可以遍历它。 My code does not return any values.我的代码不返回任何值。 Probably syntax is wrong so I would appreciate if you help me (haven't written lots in js).可能语法是错误的,所以如果你能帮助我,我将不胜感激(在 js 中没有写很多)。
Here is the html这是 html
function restore_hp(){
var percent_restore = document.querySelectorAll("table.table.table-condensed.table-top-spacing > tr > td[2]");
percent_restore.forEach((td)=>{
console.log(td.innerText)
});
}
You are probably looking for td:nth-child(2)
at the end of your selector.您可能正在选择器末尾寻找td:nth-child(2)
。
Your current td[2]
would select such a table cell: <td 2="some-attribute-value">...</td>
.您当前的td[2]
将 select 这样的表格单元格: <td 2="some-attribute-value">...</td>
。 Notice that this would be invalid HTML because a) 2
is an invalid attribut identifier (cannot start with a number) and b) even if it in general would be valid syntax it wouldn't be known for HTMLTableCellElement
, and thus again, invalid HTML.请注意,这将是无效的 HTML 因为 a) 2
是无效的属性标识符(不能以数字开头)和 b) 即使它通常是有效的语法,它也不会被HTMLTableCellElement
知道,因此同样是无效的 HTML .
2nd issue:第二期:
>
selects direct children only. >
仅选择直接子代。 tr
is not a direct child of your table
(it never is, missing tbody
is auto-inserted by all browsers). tr
不是您的table
的直接子项(它永远不会,丢失的tbody
会被所有浏览器自动插入)。
You can add a HTML class to the elements you want to manipulate and simply query on the class:您可以将 HTML class 添加到要操作的元素中,然后在 class 上简单地查询:
...
<tr>
<td>Some text</td>
<td class="my-custom-class">Some other text</td>
</tr>
...
var percent_restore = document.querySelectorAll(".my-custom-class");
percent_restore.forEach((td)=>{
console.log(td.innerText)
});
That way you're not lost in your HTML tree.这样您就不会迷失在 HTML 树中。
What you want is something called :nth-child
pseudo selector.你想要的是一个叫做:nth-child
伪选择器的东西。 Learn more from the below link- https://www.w3schools.com/cssref/sel_nth-child.asp从以下链接了解更多信息- https://www.w3schools.com/cssref/sel_nth-child.asp
SO your function may be like-所以你的 function 可能像 -
function restore_hp(){
var percent_restore = document.querySelectorAll("table.table.table-condensed.table-top-spacing tr td:nth-child(2)");
percent_restore.forEach((td)=>{
console.log(td.innerText)
});
}
Codepen: https://codepen.io/ashfaq_haq/pen/WNNOYRR代码笔: https://codepen.io/ashfaq_haq/pen/WNNOYRR
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.