Fred J.
Fred J.

Reputation: 6019

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"

Upvotes: 1

Views: 83

Answers (2)

guest271314
guest271314

Reputation: 1

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>

Upvotes: 1

kamoroso94
kamoroso94

Reputation: 1735

Since there will be many td.labels and td.values, I'd select every td.label and loop trough them comparing their textContent to "sign here" then grab the next element to work with.

var tdLabels = document.querySelectorAll("td.label");
var tdValue = null;
for(var i=0; i<tdLabels.length; i++) {
    var td = tdLabels[i];
    if(td.textContent=="sign here") {
        tdValue = td.parentNode.querySelector("td.value");
        break;
    }
}
// use tdValue somehow, but null if not found

This will find the element you're looking for and store a reference to it in tdValue. If such an element doesn't exist, it will be set to null.

Upvotes: 0

Related Questions