从TD搜索文本并获取下一个TD值,tr标签下代码失效求助
Hey there! Let's figure out why your function works for <a> or <li> tags but falls flat with <tr> ones—this is a super common DOM structure gotcha, so we’ll get it sorted quickly.
First, let’s break down the core difference between those tags:
<a>and<li>often hold text directly (like<a>find this</a>), so your code can grab their text content easily.<tr>(table rows) are container elements—they almost never hold text directly. The text you’re looking for is almost certainly inside child elements like<td>or<th>within the row.
Common Fixes & Debug Steps
Adjust your text search to look inside the row’s children
If your original code checks the<tr>element’s text directly, it might not be seeing the text nested in<td>s. Try updating your logic to either:- Check the full text content of the row (which includes all child elements’ text):
function setXWhenFound() { let X = ""; // Grab all table rows const rows = document.querySelectorAll("tr"); for (const row of rows) { // Check if the row's combined text includes your target if (row.textContent.includes("find this")) { X = "value"; break; // Stop searching once we find the first match } } return X; } - Or be more precise and search directly within
<td>elements inside rows:function setXWhenFound() { let X = ""; const cells = document.querySelectorAll("tr td"); for (const cell of cells) { if (cell.textContent.includes("find this")) { X = "value"; break; } } return X; }
- Check the full text content of the row (which includes all child elements’ text):
Debug to confirm the structure
If you’re still stuck, pop open your browser’s DevTools (F12) and:- Right-click the problematic
<tr>and select "Inspect" - In the console, type
$0.textContent(this refers to the selected element) and hit enter—check if "find this" shows up here. - If not, expand the
<tr>in the Elements panel to see exactly where the text is nested (maybe it’s in a<span>inside a<td>?).
- Right-click the problematic
Quick Note for Newbies
DOM elements can have nested structures that aren’t obvious at first—always take a second to inspect the actual HTML structure when something works for one tag but not another. It’ll save you tons of time!
内容的提问来源于stack exchange,提问作者mobus1

