0

I have a situation where I need to collect a collection of elements that have parents with IDs. So if

My scenario


<table>
 <thead></tead>
 <tbody>
   <tr id="row1"><td><div class="pro_fname">name</div></td></tr>
   <tr id="row2"><td><div class="pro_fname">name</div></td></tr>
   <tr id="row3"><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
  </tbody>
</table>

From JavaScript, how can I guarantee to store the first three fname class elements into a list, but disregard the other fname class elements, all because the first 3 have parent ID's on elements?

Below is my initial attempt...


//collect all desired elements
var objFirstNames = document.getElementsByClassName("pro_fname");
...
...

//call function to check against the array type objects collected. arguments will grow...
//lets just focus on first names
checkInputValuesObjects(objFirstNames, objLastNames, objAttEmails, ...);

//filter values where parent ID's exist
function checkInputValuesObjects() {
  for (var i = 0; i < arguments.length; i++) {
     if (arguments[i][0].parentNode.parentNode.id.length) {
       //then I can do something with these specific elements...
       console.log(arguments[i]);
    }
  }
}

...but I'm having a hard time, specifically through Firefox Console, if I am truly capturing only 3 objects, and not all 6....

isherwood
  • 58,414
  • 16
  • 114
  • 157
klewis
  • 7,459
  • 15
  • 58
  • 102

1 Answers1

2
document.querySelectorAll('tr[id] div');

Will first select all tr with an id attribute, then get all the div elements inside.

const ee = document.querySelectorAll('tr[id] div');
ee.forEach(e => console.log(e.className));
<table>
 <thead></tead>
 <tbody>
   <tr id="row1"><td><div class="pro_fname">name</div></td></tr>
   <tr id="row2"><td><div class="pro_fname">name</div></td></tr>
   <tr id="row3"><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
   <tr><td><div class="pro_fname">name</div></td></tr>
  </tbody>
</table>

The above will yield:

pro_fname
pro_fname
pro_fname
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Ok, so In this case, I should look at it from an outside -> In perspective, not from Inside -> out perspective. Many thanks! – klewis Feb 15 '22 at 19:24
  • 1
    Yes, keep in mind that CSS always works from the outside to the inside. For example CSS doesn't (really) have [a parent selector](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector). So start on the outside, and work your way in ;) – 0stone0 Feb 15 '22 at 19:26