0

Do you know why my body tag/element remains empty when I try to use it? I have the following code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/>
<title>Max</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script>
alert(document.getElementsByTagName("*"));
function se(){
  var twenty = document.getElementsByTagName("*")[20];
 //twenty.children[1].children[0].children[1].innerHTML = "hiephoi";
}
se();

var fg = document.getElementsByTagName("body")[0];//undefined
</script>
</head>
<body>
<script>
alert(document.getElementsByTagName("*"));
function se(){
  var twenty = document.getElementsByTagName("*")[20];
  //twenty.children[1].children[0].children[1].innerHTML = "hiephoi";
}
se();</script>
:
:
:

If I debug this, document.getElementsByTagName("*") does give the list of elements at breakpoint, however, letting the code run gives an error when I ask for

document.getElementsByTagName("*")[20].children[1].children[0].children[1].innerHTML = "hiephoi";

It says document.getElementsByTagName("*")[20].children is no Object, indeed it is undefined. You might wonder why I use the wildcard at all, but just looking for any specific tag returns nothing. Oddly thus, the wildcard does return a list of nodes. I could try with JQuery but I am trying to understand this. I'm thinking it might have something to do with the loading stage of the document? Or could it be that the html contains a missing tag somewhere and the JS gets confused?

Gilles 'SO- stop being evil'
  • 92,660
  • 35
  • 189
  • 229
imonaboat
  • 19
  • 6

1 Answers1

1

You are attempting to fetch the element before the DOM tree has been created. Put your javascript at the end, before the closing body tag, and see if that works (Not tested. It still may not for the same reason).

Better yet, look into window.onload to make sure the DOM is loaded before attempting to read from it. window.onload vs <body onload=""/>

Community
  • 1
  • 1
Rob
  • 13,342
  • 26
  • 40
  • 60