开发者

Why does javascript overwrite Html codes

I have just started learning javascript and my question is very basic question about javascript but i had to learn the logic behind it.

   <p id="demo">This is a paragraph.</p>

  <script type="text/javascript">
   document.getElementById("demo").innerHTML=Date();
  </script>

With these codes, only date appears on the browser and browser ignores "This is a paragraph".Should not browser write first "This is a paragraph" and below that display date?Being in the same class means, javacript overwrites every tags of the same cla开发者_开发知识库ss? Thanks


innerHTML replaces whatever HTML is there with whatever you specificy. If you want to append, you'd need to grab what is there first. Something like this:

var myTag = document.getElementById("demo");
myTag.innerHTML = myTag.innerHTML + Date();


An element's innerHTML property represents its entire contents. When you assign a new value to it, you replace the entire contents. It sounds like you want to use += instead of = so that you append to the existing string rather than replacing it.


innerHTML replaces the text inside the element that it is invoked on with what you pass to it, hence "This a paragraph" will be replaced by the value of date.

Try this instead:

document.getElementById("demo").innerHTML = 
  document.getElementById("demo").innerHTML + Date();


Should not browser write first "This is a paragraph" and below that display date?

Seems that you want a line break and then the date.

Do this to accomplish that without destroying the existing content:

var demo = document.getElementById("demo");

demo.appendChild( document.createElement( 'br' ) );
demo.appendChild( document.createTextNode( Date() ) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜