Javascriptをはじめ、Ajax、jQueryの著書多数のガイドが、何かと最近騒がれているJa…
北欧好きが、愛用の北欧モノを見せ合うコミュニティ
Javascript関連情報
更新日:2006年02月26日
今回は、ページのHEAD内でDOM要素生成してエラーに見舞われた方や、ページ構築完了後、onloadでスクリプトを開始するまでの間ユーザーを待たせるのがつらいという方限定の少し偏った(?)Tipsです。

<html>
<head>
<script type = "text/javascript">
<!--
if(document.getElementsByTagName('BODY').length==0)
document.write('<body>');//←ダミーのbodyタグを出力
var ele = document.createElement('DIV');
ele.setAttribute('id','testDIV');
ele.setAttribute('width','200');
ele.style.color = 'red'
ele.innerHTML="test";
document.body.appendChild(ele); //←エラーになりません
//-->
</script>
</head>
<body>←body要素の開始位置
</body>
</html>
<html>
<head>
<script type = "text/javascript">
<!--
alert('1::'+document.getElementsByTagName('BODY').length)
if(document.getElementsByTagName('BODY').length==0)
document.write('<body>');//ダミーのbodyタグを出力
var ele = document.createElement('DIV');
ele.setAttribute('id','testDIV');
ele.setAttribute('width','200');
ele.style.color = 'red'
ele.innerHTML="test";
document.body.appendChild(ele); //←エラーになりません
alert('2::'+document.getElementsByTagName('BODY').length)
//-->
</script>
</head>
<body onload="alert('onload::'+document.getElementsByTagName('BODY').length)">
</body>
<script type = "text/javascript">
<!--
alert('3::'+document.getElementsByTagName('BODY').length)
//-->
</script>
</html>
結果(Win e6,e7b,f1.5,o8,o9b, Mac s1.24,s2,e5, Linux k3)
1::0
2::1
3::1
onload::1
つまり、ダミーのbodyタグをdocument.writeした時点で、BODYオブジェクトが生成され、その後、HTMLで書かれたBODYが出現しても、そのオブジェクトは1個のまま増えません。
if(document.body==null)document.write('<body>');
if(!document.body)document.write('<body>');
document.body||document.write('<body>');
document.write((document.body)?'':'<body>');
いずれの方法でも、同様に、スクリプト処理の時点でBODYタグが存在しなければ、その場で出力してくれます。 人気Javascriptランキング
Powered by 価格.com
北欧好きが、愛用の北欧モノを見せ合うコミュニティ