I need to find the siblings of one element. The object I desire to get is nested input. The code belove navigates to td[2] where I need to do some comparison. Afterwords when the comparison is made I need to get to td[4] which contains input. I did try to use nextsibling function but something goes wrong:( Here is the image of 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.
You can track the element's siblings with the example introduced in the MDN documentation here .
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. You might be mistaking it for JQuery.
Instead, you want to use 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.