-2

this is my tbody structure

  <tbody class="tbl_documents_body">
    <tr>....</tr>
    <tr>....</tr>
    <tr>....</tr>
  </tbody>

select tbody by class name and print it on console:

let tr = document.getElementsByClassName('tbl_documents_body');
console.log('tr',tr);

will show the tbody element on console, like this:

tr 
HTMLCollection [tbody.tbl_documents_body]
0: tbody.tbl_documents_body
length: 1
[[Prototype]]: HTMLCollection

there are plenty of things if I click 0:

enter image description here

and if I add [0] like this:

let tr = document.getElementsByClassName('tbl_documents_body')[0];
console.log('tr',tr);

it will only show all the tr inside the body:

enter image description here

I wonder why it works like this.

thanks!

Grace
  • 7
  • 1
  • You have to look at what those functions actually return. Its not an array. – chovy Jul 09 '22 at 10:54
  • @chovy It's not an actual array, but an array-like structure. But this doesn't have anything to do with the actual question/problem – Andreas Jul 09 '22 at 11:00
  • See [*What do querySelectorAll and getElementsBy\* methods return?*](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) (I should have voted to close as duplicate, used wrong close reason). – T.J. Crowder Jul 09 '22 at 11:03
  • @T.J.Crowder Isn't the actual problem the one in the title (with the body being a slightly modified version of that) -> querying the class of the `` element doesn't return the children of that element but the element itself (wrapped in a collection) – Andreas Jul 09 '22 at 11:08
  • @Andreas - ...Maybe? @​Grace - If so, it's because browsers show you the most useful rendering (in the eyes of their devs) of what you evaluate in the console. When you ask the console to show you an HTML element, it shows you an interactive rendering in an HTML-like format where you can see the structure, expand child elements to see what's inside them, etc. But when you asked it to show you the `HTMLCollection` from `getElementsByClassName`, that's not an HTML element, so it used its rendering for objects instead, and having started out that way, continues doing that rather than changing. – T.J. Crowder Jul 09 '22 at 11:14

1 Answers1

2

document.getElementsByClassName is returning an HTMLCollection (which is array like).

So when you use document.getElementsByClassName, you get a collection of elements matching the class name. In you case only a single element have the tbl_documents_body class.

When you access the first item in the collection [0] you get the tBody element itself, thus you can inspect it's properties.

Omri Attiya
  • 3,917
  • 3
  • 19
  • 35