Elements out of scope in Javascript?

So here's my problem: When I use the javascript document.write() statement to write html to a page, it works fun and good and I can do stuff like

for(i = 0, i < rows, i++)

{

document.write("<tr>");

for(j = 0, j < columns, j++)

{

document.write("<td></td>");

}

document.write("</tr>");

}

Now I just give it variables and it creates a dynamic table, right? Great.

But when I write something dynamically like that, and specify its "id" attribute, it's inaccessible. For instance, suppose the line:

document.write("<td></td>");

instead read:

document.write("<td id=\""+i+""+j+"\"></td>");

Now I would expect each cell to have an id like, 00, 01, 02, 03... until I reach the last row/column pair.

While this seems to work, if I try to get at that element using javascript functions like this:

var cell = document.getElementById("00");

always ends up returning null

Why is this? What am I doing wrong, and why is it working this way.

Here is another simple example where I get null values for elements by id:

<html>

<head>

<script type="text/javascript">

document.write("Head");

function cell()

{

document.writeln("In cell()");

var tbl =document.getElementById("myTable");

document.writeln("myTable: "+tbl);

tbl.bgColor = document.getElementById("selBox").selectedIndex.text;

}

</script>

</head>

<body>

<script type="text/javascript">

document.write("Body");

document.write("<table id=\"myTable\" border=\"1\"><tr><td>cell 1</td><td>cell 2</td></tr><tr><td>cell 3</td><td>cell 4</td></tr></table>");

document.write("<br />");

document.write("<select id=\"selBox\" onclick=\"cell()\" value=\"Alert first cell\"><option>Blue</option></select>");

</script>

</body>

</html>

Please let me know what I'm doing wrong, and why it doesn't work like I expect. Thanks

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    I think to use the DOM hierarchy to add tags in place then the

    document.getElementById() method would work fine

    try out this link it has a small tutorial

    http://javascriptkit.com/javatutors/dom2.shtml

  • Anonymous
    4 years ago

    Javascript is its very own language. in trouble-free terms idiots think of Java and JavaScript are appropriate. the only relation the two have is they're the two programming languages. SCOPE: Javascript runs in all substantial browsers and is area of fairly some purposes (adobe reader, for one). power: javascript makes static webpages dynamic. it is likewise achievable to place in viruses with javascript (that's why it extremely is risky) yet i cant clarify the way it does it because of the fact i dont know. you study javascript with the aid of getting to grasp javascript. there are actually not any situations. inspite of the shown fact that it extremely is a good theory to already know HTML.

Still have questions? Get your answers by asking now.