...

View Full Version : Can't Figure Out - document.getElementById



hiyatran
05-28-2012, 12:12 AM
I'm trying convert document.write to document.getElementById
but it is not working and I can't seem to figure it out.



This is my original code:

var myurl = new Array("google.com", "yahoo.com");

for (i=0;i<=myurl.length-1;i++){
document.write("<a href='http://www." + myurl[i] + " target='_blank'>"+ myurl[i]+"</a>");
}
I would like to convert to document.getElementById but it doesn't work.



<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<script type="text/javascript">

var myurl = new Array("google.com", "yahoo.com");

document.getElementById('info').innerHTML = "<table border=1><tr><td>";

for (i=0;i<=myurl.length-1;i++){
document.getElementById('info').innerHTML += "<tr><td><a href='http://www." + myurl[i] + " target='_blank'>"+ myurl[i]+"</a></tr></td>";
}
document.getElementById('info').innerHTML = "</tr></td></table>";
</script>
</HEAD>

<BODY>


<p id="info"></p>

</BODY>
</HTML>

chump2877
05-28-2012, 12:59 AM
<HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<script type="text/javascript">
var myurl = new Array("google.com", "yahoo.com");
var infoContent = "<table border=1><tr><td>";
for (i=0; i<=myurl.length-1; i++)
{
infoContent += "<a href='http://www." + myurl[i] + " target='_blank'>"+ myurl[i]+"</a>";
}
infoContent += "</tr></td></table>";
document.getElementById('info').innerHTML = infoContent;
</script>
</HEAD>
<BODY>
<p id="info"></p>
</BODY>
</HTML>

felgall
05-28-2012, 03:58 AM
The script needs to go at the bottom just before the </body>

The id has to exist before you can reference it.

low tech
05-28-2012, 04:04 AM
I don't think it is legal html to put a table inside a paragraph, is it?

LT

Philip M
05-28-2012, 09:11 AM
I don't it is legal html to put a table inside a paragraph, is it?

LT

Correct. You can't put a <table> inside a <p>.

So you're trying to insert invalid HTML and the browser will change <p><table></table></p> into <p></p><table></table> (i.e. moving the table child up to a sibling) in order to get valid HTML.

If you give the browser invalid HTML, the browser will guess what you really mean and go with its guess.


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum