Jump to content

Setting Inner Text of a DIV tag


nuwandias

Recommended Posts

Hi everyone.., I have the following code which sets the inner text of a div tag by JavaScript. But this only works in Internet Explorer, i tried it with Mozilla Firefox but it doesn't work even in the latest version.<html> <head> <title>Test Inner Text </title> <script language="JavaScript"> function setInnerText(){ document.getElementById('tag').innerText = "This is the Inner Text"; } </script> </head> <body> <div id="tag"> </div> <input type="button" value="Click to test" onClick="setInnerText()"/> </body></html>If there is anyone who can tell me why this does not work in firefox and what else should i do to make it work in firefox i would really appreciate their effortThanks and Regards,Nuwan

Link to comment
Share on other sites

If there is anyone who can tell me why this does not work in firefox and what else should i do to make it work in firefox i would really appreciate their effort
Firefox doesn't support "innerText" anymore. You have to use "textContent" instead. Which means, for compatibilty's sake, you'll have to find out which browser the user is using, and use the appropriate property.Also, as an added note you shouldn't use the "language" attribute, you should use " type="text/javascript" " instead. And the "onClick" should be all lowercase. I think that's probably just for XHTML... but it's a good habit to get into.For your code to work in Firefox you would use;
<html><head><title>Test Inner Text </title><script type="text/javascript">function setInnerText(){document.getElementById('tag').textContent="This is the Inner Text";}</script></head><body><div id="tag"></div><input type="button" value="Click to test" onclick="setInnerText();" /></body></html>

Of course, if you're using XHTML, then you'd include the appropriate doctype and html namespace stuff...And depending on what you're using you can alway use the "innerHTML" property instead. But it will try to read what you put in as code, so any "<"s or ">"s could mes things up.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...