Fred J. Fred J. - 1 year ago 76
Javascript Question

Selecting element from a DOM using JS

This selector

needs to target the
element which is the next sibling of another
which has the text "sign here" so that the image appended after the "abc:".

How can it be done? Thanks

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

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

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


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

Answer Source

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


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download