简体   繁体   English

如何在兄弟姐妹中获得嵌套选择器

[英]how to get nested selectors in siblings

I need to find the siblings of one element.我需要找到一个元素的兄弟姐妹。 The object I desire to get is nested input.我希望得到的 object 是嵌套输入。 The code belove navigates to td[2] where I need to do some comparison.代码 belove 导航到 td[2] 我需要做一些比较。 Afterwords when the comparison is made I need to get to td[4] which contains input.之后进行比较时,我需要到达包含输入的 td[4] 。 I did try to use nextsibling function but something goes wrong:( Here is the image of html: HTML我确实尝试使用 nextsibling function 但出了点问题:(这是 html 的图像: HTML

var inputs = document.querySelectorAll("table.table.table-condensed.table-top-spacing tr td:nth-child(2)");
    inputs.forEach((input)=>{
        var final_input = input.find("input[name='quantity']");
        final_input.click;
    });

According to docs Using Node.nextSibling Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element.根据文档 Using Node.nextSibling Node.firstChildNode.previousSibling可能指的是空白文本节点而不是实际元素。

You can track the element's siblings with the example introduced in the MDN documentation here .您可以使用此处MDN 文档中介绍的示例跟踪元素的兄弟姐妹。

var el = input;
i = 1;

while (el) {
  if(el.nodeName ==="TARGET_ELEMENT")
      break;
  console.log(i, '. ', el.nodeName);
  el = el.previousSibling;
  i++;
}

I think the root cause of your problem is that find is not a method that exists on HTML elements.我认为您的问题的根本原因是find不是 HTML 元素上存在的方法。 You might be mistaking it for JQuery.您可能会将其误认为 JQuery。

Instead, you want to use parentElement.querySelector :相反,您想使用parentElement.querySelector

 const cells = document.querySelectorAll('table tr td:nth-child(2)'); cells.forEach(cell => { if (cell.textContent === '1') { const input = cell.parentElement.querySelector('input[name="quantity"]'); input.value = 'matched'; } })
 <table> <tr> <td>cell</td> <td>1</td> <td>input</td> <td><input type="text" name="quantity" /></td> </tr> <tr> <td>cell</td> <td>0</td> <td>input</td> <td><input type="text" name="quantity" /></td> </tr> <tr> <td>cell</td> <td>1</td> <td>input</td> <td><input type="text" name="quantity" /></td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM