问题描述:

How do I go about getting a reference to an element nested inside another element I can find by getElementByID()?

I have this so far:

<table>

<tr id="templateRow" style="display: none;">

<td><input name="f_name[]" type="text"></td>

<td><textarea name="f_description[]" rows="4"></textarea></td>

<td><input name="f_category[]" type="text"></td>

</tr>

</table>

and have some JS that adds in copies of that to build out the table (removing the id and style attributes as I go).

Assuming I have a reference to the <tr>, how do I reference the input named f_name[] within that table row?


Background: For the moment I have temporary id's on the nested elements, removing them too as I go. The tricky situation I have is that I have a function that adds 1 row (and returns a reference to it), and another function that adds multiple rows (calling the addOneRow function) .. and I want the addManyRows function to end up setting the focus on the first row added.

网友答案:

In any reasonably recent browser, you can use the querySelector method to query for children of the element.

Example:

var templateRow = document.getElementById('templateRow');

var f_name = templateRow.querySelector('[name="f_name[]"]');
var f_description = templateRow.querySelector('[name="f_description[]"]');
var f_category = templateRow.querySelector('[name="f_category[]"]');

console.log(f_name.outerHTML);
console.log(f_description.outerHTML);
console.log(f_category.outerHTML);
<table>
<tr id="templateRow" style="display: none;">
  <td><input    name="f_name[]"         type="text"></td>
  <td><textarea name="f_description[]"  rows="4"></textarea></td>
  <td><input    name="f_category[]"     type="text"></td>
</tr>
</table>
网友答案:

Use Element#querySelector method and where use attribute equals selector to get based on the attribute.

tr.querySelector('td input[name="f_name[]"]')

var tr = document.getElementById('templateRow');

tr.querySelector('td input[name="f_name[]"]').style.color = 'red';
<table>
  <tr id="templateRow" style="">
    <td>
      <input name="f_name[]" type="text">
    </td>
    <td>
      <textarea name="f_description[]" rows="4"></textarea>
    </td>
    <td>
      <input name="f_category[]" type="text">
    </td>
  </tr>
</table>
相关阅读:
Top