0

I have a document which is rendered to a following structure:

<tr>
    <td>
        <div class="csLabel">
            <label for="common_id">Label</label>
        </div>
    </td>
    <td>
        <div class="csFields">
            <select id="common_id" name="someName">
                <option value="">some options...</option>
            </select>           
        </div>
    </td>
</tr>

There are many elements of such on a page and I want to hide only few of them. As you can see, there are two elements: a label and select. They both share the same value common_id but in label it is assigned to for attribute and in select it is id.

Is there a way to get all such elements that use the value common_id?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
mate00
  • 2,727
  • 5
  • 26
  • 34

2 Answers2

1

Have a try with this

If you want to just hide the row you only need the ID:

var id = "common_id2";
[...document.querySelectorAll("#"+id)].forEach(function(ele) {
  ele.closest("tr").style.display="none";
})
<table>
  <tbody>
    <tr>
      <td>
        <div class="csLabel">
          <label for="common_id1">Label</label>
        </div>
      </td>
      <td>
        <div class="csFields">
          <select id="common_id1" name="someName">
            <option value="">some options...</option>
          </select>
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="csLabel">
          <label for="common_id2">Label</label>
        </div>
      </td>
      <td>
        <div class="csFields">
          <select id="common_id2" name="someName">
            <option value="">some options...</option>
          </select>
        </div>
      </td>
    </tr>
  </tbody>
</table>

If the label and element are in different rows you need both ID and for=ID

var id = "common_id2";
[...document.querySelectorAll("#" + id + ", [for=" + id + "]")].forEach(function(ele) {
  ele.closest("tr").style.display = "none";
})
<table>
  <tbody>
    <tr>
      <td>
        <div class="csLabel">
          <label for="common_id1">Label</label>
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="csFields">
          <select id="common_id1" name="someName">
            <option value="">some options...</option>
          </select>
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="csLabel">
          <label for="common_id2">Label</label>
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <div class="csFields">
          <select id="common_id2" name="someName">
            <option value="">some options...</option>
          </select>
        </div>
      </td>
    </tr>
  </tbody>
</table>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Maybe do this on load, then what you need to do later will be much easier.

const child = document.querySelectorAll('label[for="common_id1"]')

child.forEach(node => node.parentNode.parentNode.data('targetId', node.id))

etoxin
  • 4,908
  • 3
  • 38
  • 50