I’m having this problem where I’m unable to narrow the span of getElementsByTagName.
this is what I’m doing
<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
var t = document.getElementById("t");
var x = t.getElementsByTagName("table");
//var f = x.getElementsByTagName("td");
alert(x.length);
}
</script>
</head>
<body>
<div id="t">
<table class="x">
<td class="f">
</td>
</table>
</div>
<input type="button" onclick="getElements()" value="How many input elements?">
</body>
</html>
the above works, brings back 1.
though when I change this.
var f = x.getElementsByTagName("td");
alert(f.length);
it breaks the script.
how I’m I able to narrow it when I’m unable to use 2 TagNames?
UPDATE: my bad, I realised after posting this that it has to have [0] after the var.
var t = document.getElementById("t");
var x = t.getElementsByTagName("table");
var f = x[0].getElementsByTagName("td");
var u = f[0].getElementsByTagName("div");
alert(f.length);
alert(u[0].className);
That is because
getElementsByTagNamealways returns an array, even if there is only one element.If you do
var f = x[0].getElementsByTagName("td");it should work properly.