Fred J. Fred J. - 3 months ago 6
Javascript Question

Selecting element from a DOM using JS

This selector

doc.getElementsByClassName('value')
needs to target the
td
element which is the next sibling of another
td
which has the text "sign here" so that the image appended after the "abc:".

How can it be done? Thanks

let w = window.open();
let doc = w.document;
doc.write(raw_html);
doc.close();
let sigImg = new Image();
sigImg.src = signature;
doc.getElementsByClassName('value').appendChild(sigImg); //wrong selector


There are many of
td
and tr element with different class and values.

<tr>
<td class="label">sign here</td>
<td class="value">abc:</td>
</tr>


edit

The element index is not known in advance. only that it is after another
td
element which has its text equal to "sign here"

Answer

document.getElementsByClassName returns an HTMLCollection. Use bracket notation to select element at specific index; e.g., [0] to select element at index 0 of returned collection

doc.getElementsByClassName('value')[0].appendChild(sigImg);

To select element where previous element text contains "sign here" you can iterate all elements having className "value", check if element .previousElementSibling .textContent is equal to required text

<table>
  <tbody>
    <tr>
      <td class="label">sign here</td>
      <td class="value">abc:</td>
    </tr>
    <tr>
      <td class="label">do not sign here</td>
      <td class="value">def:</td>
    </tr>
  </tbody>
</table>
<script>
  var sigImg = new Image;
  sigImg.src = "http://lorempixel.com/50/50";
  for (var elem of document.getElementsByClassName("value")) {
    if (elem.previousElementSibling.textContent === "sign here") {
      elem.appendChild(sigImg); break;
    }
  }
</script>

Comments