I’m trying to make a generic JavaScript function to obtain a collection of entries within a tag. For example:
With a list
<ul class="collection">
<li>First Entry</li>
<li>Second Entry</li>
<li>Third Entry</li>
</ul>
With divs
<div class="collection">
<div >First Entry</div >
<div >Second Entry</div >
<div >Third Entry</div >
</div>
With tables
<table class="collection">
<tr>First Entry</tr>
<tr>Second Entry</tr>
<tr>Third Entry</tr>
</table>
Here’s what I have:
function getEntry(a)
{
var elementCollection = document.getElementsByTagName('*');
for(var i = 0; i < elementCollection.length; i++)
{
if(elementCollection[i].className.toString() === "collection")
{
var filteredCollection = elementCollection[i].children;
alert(filteredCollection[a].innerHTML);
}
}
}
This does exactly what I want if I deal with lists or divs, but when I run that through a table he gives the me all entries if a=0 or nothing if a!=0
Do tables behave differently or am I doing something wrong?
Yes, your HTML is invalid because it doesn’t include a
<tbody>element, so the browser is inserting it for you, as is the case with the table cells.So when you get to your
table, and use.children[0], you’re getting the new<tbody>element, which contains all the<tr>elements, which explains why it gives you all the entries.And of course if you use
.children[1]or anything greater than0, there is no child because you only have the onetbody.