Click to See Complete Forum and Search --> : Why the hoo haa with innerHTML


Shaolin
07-30-2008, 12:02 PM
Hi Guys

I've noticed people looking down when one uses innerHTML. They say that it doesn't fall into the W3C DOM standards. But should it really be a problem ? I am developing a site and I will be moving around very large chunks of code and the best way to do this without using too much JS is to simply use innerHTML. If I used dom then my JS would be huge and not to forgot alot more slower. So why all this woohaa over something which has many benefits ?

HoboScript
07-30-2008, 12:23 PM
Because the only benefit is what you just listed. Its good for moving and copying large amounts of inside code. However, if you want to edit just one attribute on one element. Its useless. You also lose all ability to use any DOM specific methods of create and attaching elements when using innerHTML. If you are not moving a large amount of inside HTML from one location to another, it's foolish and lazy to use.

scragar
07-30-2008, 12:38 PM
can I add that redrawing the whole page(which is what normaly happens when innerHTML is used) is a fairly intensive operation for small amounts of data, not to mention the flicker users may see. Can I also add that DOM can very more effective than innerHTML for many tasks, consider code below for example:
// we want 10 tr's, each with 10 tds, big requirement

// DOM method

var table = document.getElementById('TehTable');
var tr = document.createElement('tr');
var td = document.createElement('td');
var i;
for(i = 0; i < 10; i++)
tr.appendChild(td.cloneNode(false));
for(i = 0; i < 10; i++)
table.appendChild(tr.cloneNode(true));

// innerHTML method
var table = document.getElementById('TehTable');
var tr = '<tr>';
var td = '<td></td>';
var i;
for(i = 0; i < 10; i++)
tr += td;
tr += '</tr>';
for(i = 0; i < 10; i++)
table.innerHTML += tr;

Declan1991
07-30-2008, 12:46 PM
It also doesn't add elements into the DOM tree, so you often cannot get them by document.getElementById.

Kor
07-30-2008, 12:53 PM
innerHTML is not a standard DOM method, thus it does not always (or it does incomplete) insert the elements as true DOM elements.

Some quick examples (among many others):
- innerHTML can not "copy" the dynamic changed value of an input (Moz, Opera)
- innerHTML can not insert new rows into a table (IE)

innerHTML is faster, and good in case you need only to display some things on the documents, but not when you need to work with the DOM tree afterwards. DOM methods are safer and give a better control over the elements, attributes, values, events...

slaughters
07-30-2008, 01:36 PM
Hi Guys

I've noticed people looking down when one uses innerHTML. They say that it doesn't fall into the W3C DOM standards. But should it really be a problem ?...It is just as standard as using the offsetWidth and clientWidth element properties, which are *not* W3C spec either. I guarantee that a huge chunk of people who sneer at innerHTML use don't bat an eye when using offsetWidth to find the width of a DOM element.

You can always do an innerHTML assignment and then later on use DOM to inspect the individual components. (Note: after reading what Kor said - I've not noticed it, but if he said it does not work 100% of the time then I'll believe him)

My rule of thumb is that if I rigidally control what is going on, ie I *know* I will create a table. I *know* column 1 will be an image, column 2 a hyperlink, column 3 a bolded text element, etc. Then I'll probably use DOM methods.

If I do not know exactly what it will be, like the input is from a rich text editor, or a mixed media message, or the source HTML from an iframe, etc. Then I'll probably use innerHTML

Declan1991
07-30-2008, 03:16 PM
The handiest thing about the W3C methods are that you can refer to the element again without using document.getElementById or a similar method. I try to use them as often as possible, because at least with them, I'm less likely to run into the innerHTML problems (I personally never have, but I remember a problem a few weeks ago here caused by innerHTML). I have no problems using it when it's easier though.

felgall
07-30-2008, 04:30 PM
None of the Browser Object Model is defined by the W3C so if you want to reference browser settings you MUST use the proprietary ones provided by the browser itself (fortunately most browsers have implemented the Firefox version so you only need worry about two alternatives to cover 99.9% of browsers).

innerHTML is not supported at all in XHTML so if you want to make it easy to convert your page to XHTML in the future you would use the DOM methods. Changing from the HTML version of the DOM methods to the XHTML equivalents is then a straightforward substitution of one method for the other rather than requiring a complete rewrite to replace innerHTML.

slaughters
07-30-2008, 05:14 PM
...the Firefox version...I thought it was the IE version ?

I don't know the nitty gritty by any means, but I keep seeing links from Mozillas developer site to MSDN for things like offsetWidth, scrollWidth, clientWidth, innerHTML, etc..

http://developer.mozilla.org/en/docs/DOM:element.offsetWidth

Did Mozilla just come up with a cleaner Browser Object Model for Firefox that incorporated the functionality of properties that Microsoft came up with originally ? Made it more manageable so to speak ?

P.S.

As a developer I've found that the words "straightforward" and "substitution" tend to not go together very well :)

Declan1991
07-30-2008, 05:28 PM
As a developer I've found that the words "straightforward" and "substitution" tend to not go together very well :)
I agree there, but Felgall is certainly right. If you use XHTML served as text/html and innerHTML (or document.write etc.) you are just kidding yourself. At least with document.createElement in XHTML, it's a minor change to have it working correctly in XHTML, but with innerHTML, a total rehaul of the JavaScript is needed.

slaughters
07-30-2008, 05:35 PM
True,

But my favorite quote about XHTML comes from Wikipedia:

"With limited browser support for the alternate application/xhtml+xml media type, XHTML 1.1 has so far proven unable to gain widespread use."

http://en.wikipedia.org/wiki/XHTML#XHTML_1.1.E2.80.94Module-based_XHTML

:)

Declan1991
07-30-2008, 05:52 PM
My favourite has always beenHTML 4.01 contains everything that XHTML 1.0 contains, so there is little reason to use XHTML in the real world. It appears the main reason is simply "jumping on the bandwagon" of using the latest and (perceived) greatest thing.
I think that last line is very true.

felgall
07-30-2008, 09:19 PM
True,

But my favorite quote about XHTML comes from Wikipedia:

"With limited browser support for the alternate application/xhtml+xml media type, XHTML 1.1 has so far proven unable to gain widespread use."

http://en.wikipedia.org/wiki/XHTML#XHTML_1.1.E2.80.94Module-based_XHTML

:)


By limited support they mean that only 999 out of 1000 browsers support XHTML with Internet Explorer being the odd one out.

Now that IE has a falling market share the support for XHTML is growing rapidly and is just about to pass 50% of all web users having a browser that supports it. It is nowhere near as limited now as it was two years ago when less than 5% of people used a browser that supports it.


The other consideration regarding using the DOM rather than innerHTML is the same argument as for using HTML instead of XHTML in that there is better support and it will work more of the time.

Kor
07-31-2008, 02:10 AM
You can always do an innerHTML assignment and then later on use DOM to inspect the individual components. (Note: after reading what Kor said - I've not noticed it, but if he said it does not work 100% of the time then I'll believe him)

You bet :) :
Example 1 - FF3 and Opera9 do not "copy" the dynamically input value of a text field (XHTML strict Doctype)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
/*<![CDATA[*/
function addInput(){
var root=document.getElementById('myform');
root.innerHTML+=root.innerHTML;
}
/*]]>*/
</script>
</head>
<body>
<form id="myform" action="">
insert some text in the textfield than blur it
<input type="text" onchange="addInput()">
</form>
</body>
</html>

Example 2: IE does not insert new rows into a table (HTML strict Doctype)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function addRow(tbody){
tbody.innerHTML+='<tr><td onclick="addRow(this.parentNode.parentNode)">addRow</td></tr>';
}
</script>
</head>
<body>
<table style="width:100px;border:solid 1px #000">
<tbody>
<tr><td onclick="addRow(this.parentNode.parentNode)">addRow</td></tr>
</tbody>
</table>
</body>
</html>


Now that IE has a falling market share the support for XHTML is growing rapidly and is just about to pass 50% of all web users having a browser that supports it. It is nowhere near as limited now as it was two years ago when less than 5% of people used a browser that supports it.

Regarding the XHTML... Well, hm... An important key figure in the Web history, Brendan Eich (http://weblogs.mozillazine.org/roadmap/), the inventor of Javascript, set his heart rather upon ECMAScript 4 (http://www.ecmascript.org/es4/spec/overview.pdf) (Javascript 2) and HTML 5 (http://www.whatwg.org/specs/web-apps/current-work/) in opposition with the advance of the XHTML for the future. After all, XHTML has sense only if you handle XML files on the document, or this is not happen so often, as XML has a serious concurrent in JSON for data transfer.

Shaolin
07-31-2008, 12:06 PM
Thanks for the reply guys. How about this, I innerHTML all of the static content and the dynamic content I will update using DOM ? Since I am using servlets to output html then I simply throw it onto the page using innerHTML.

mrhoo
07-31-2008, 03:36 PM
There is nothing wrong with either innerHTML or document.create methods-
it's what you can do with them that means anything.

innerHTML is the Tin Man of scripting, but you don't always need a Terminator 2000 to get the job done.

rnd me
07-31-2008, 06:43 PM
Did Mozilla just come up with a cleaner Browser Object Model for Firefox that incorporated the functionality of properties that Microsoft came up with originally ? Made it more manageable so to speak ?


yes, they have added several IE dom MPEs to firefox3.

Kor
07-31-2008, 10:04 PM
As long as it is crossbrowser and works exactly how you need, keep the innerHTML. As I said, it is faster. As long as you will encounter some problems, be sure that you have overpass the innerHTML limits and you should consider a DOM solution.

slaughters & rnd_me:

Both IE and Moz brought good ideas. innerHTML is a good quick tool (especially in simple AJAX applications) when you don't need further DOM maneuvers. And if innerHTML is not a W3C standard method, that does not means it is so evil, as it was implemented in Moz as well.

After all, W3C (and I think ECMA too) is IE and Moz and Opera and so on. W3C has in its board representatives of all the main browsers' builders. But, same as in democracy, the majority gives the rules. Remember that W3C gives recommendations, not verdicts.

Don't think in absolute black vs white like: IE is evil - Moz is angel. After all there are some absolute bright minds in both armies, aren't they? :) And they lately started to meet half way : Moz has implemented IE's innerHTML and onbeforeunload methods, IE7 works now with the XMLHttpRequest object... Javascript/DOM is much more a common language now than, say, about 10 years ago (when you had to code everything in mirror: IE document.all / Netscape document.layers). Let's hope for even better in the future :)

Shaolin
08-01-2008, 10:14 AM
Thanks for the replies guys.

Kor: Well, it does work so thats no problem. But I will be adding a search feature, so when a user enters a name then it will update the results realtime (adding/deleting table rows). The user will also beable to apply filters to records, delete them and so on. Now, if I use innerHTML to load *ALL* the content into the browser then user DOM to edit/update table content would that work? My second option is to load all the images/css/colors using innerHTML and simply add the tables using DOM. Which one would you recommend? (anyone can comment)

Kor
08-01-2008, 12:41 PM
It is hard to say. innerHTML acts like a real DOM method now and then. It depends on the elements you have to append.

For me, I would have used definitely only DOM standard.

Shaolin
08-01-2008, 01:18 PM
Well, its only appending/deleting TRs. I could output the TRs in a html file (produced by the server) and use innerHTML to place it into the appropriate element ID or get the server to produce an XML and update the Table accordingly ?

felgall
08-01-2008, 05:06 PM
You can't append TRs using innerHTML in Internet Explorer - in IE it only works for the whole table or the content of one TD and not for parts of tables. Parts of tables can only be inserted with innerHTML in browsers other than IE.

Singleton
09-17-2008, 10:20 PM
It also doesn't add elements into the DOM tree, so you often cannot get them by document.getElementById.
You ought to try it first.

felgall
09-17-2008, 11:38 PM
You ought to try it first.

I did try it once and found that it doesn't work in all browsers.

You can't mix innerHTML and the DOM that way unless you are only targetting one browser that happens to allow wghat you are trying.

Singleton
09-17-2008, 11:45 PM
Please show me.

HoboScript
09-18-2008, 12:30 AM
Please show me.

Seems to work fine in Opera 9 and FireFox 3. These are both latest browsers and not proof what-so-ever. Interesting though to note that the DOM was updated.

Singleton
09-18-2008, 12:31 AM
Are you sure?

Kor
09-18-2008, 01:51 AM
Interesting though to note that the DOM was updated.
DOM updated? I don't think so. The W3C DOM Activity is closed since 2004. So far only some Working Groups continue to develop some API's, but the last DOM core, DOM3, is still there since 2004, while only some small developments were made.

http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/

Never heard about a recent "DOM update".

felgall
09-18-2008, 02:13 AM
DOM updated? I don't think so.

Never heard about a recent "DOM update".

The reference is to the DOM tree for the web page being updated not the DOM standard.

Perhaps it is the case with the latest versions of all browsers now but you couldn't use getElementById on an element inserted using innerHTML in the latest browsers that existed two years ago and there are still some people using those browsers so mixing the two still will not work for everyone.

monshio
09-18-2008, 06:14 AM
Because innerHTML will clear every elements and HTML that you may already have in your element, so it happens if you innerHTML the element but some times if you use DOM to createElement() and appendChild() it will be the solution to keep your codes and HTML in that element and also append new element into the tag.

Homepage (http://www.mamad.net)

aj_nsc
09-18-2008, 07:56 AM
I may be taking a step back here because the discussion seems to have gone way beyond what the OP meant, but, as regards to the OP, I know what you are getting at and, if I were you, I think you could very easily use the 'standard' DOM method instead of innerHTML, you probably just don't realize it.

If you are moving very large chunks of code, there are probably only a few top level parent nodes in the code you are dealing with. All you need to do is grab the top level parent nodes using removeChild or cloneNode and then insert it somewhere else using insertBefore, appendChild. When you just grab the parent node in a variable, you are preserving the underlying DOM structure of all the child elements. Plus, if all you are doing is 'moving' elements around, then you shouldn't ever need to use createElement.

The reason why I am suggesting this is because most people who are just starting out in using Javascript and the DOM start out with using .innerHTML, and this implies to me, which could be completely incorrect, that the OP really hasn't delved that deeply into how powerful Javascripts ability to modify the DOM is. If this is the case, and again I apologize if it isn't, perhaps you should take a look at my favorite site on the net: http://www.javascriptkit.com/domref/

As a lot of other people in this thread have pointed out, there is nothing wrong with using innerHTML as long as you don't have to do anything with this innerHTML afterwards using DOM methods, because it's unreliable cross-browser, but, if you are positive that you AREN'T going to do anything with the moved around elements after (and you can positively foresee never needing to do anything with it later on in your development), then by all means I would use innerHTML, too. As you said, it's just easier and faster.

Singleton
09-18-2008, 10:46 AM
The reason why I am suggesting this is because most people who are just starting out in using Javascript and the DOM start out with using .innerHTML, and this implies to me, which could be completely incorrect, that the OP really hasn't delved that deeply into how powerful Javascripts ability to modify the DOM is. If this is the case, and again I apologize if it isn't, perhaps you should take a look at my favorite site on the net: http://www.javascriptkit.com/domref/


JavaScript doesn't actually have anything to do with the DOM. JavaScript is available for more than just the web.


As a lot of other people in this thread have pointed out, there is nothing wrong with using innerHTML as long as you don't have to do anything with this innerHTML afterwards using DOM methods, because it's unreliable cross-browser, but, if you are positive that you AREN'T going to do anything with the moved around elements after (and you can positively foresee never needing to do anything with it later on in your development), then by all means I would use innerHTML, too. As you said, it's just easier and faster.

What's the cross-browser problem? Can you please demonstrate?

Kor
09-18-2008, 11:07 AM
The reference is to the DOM tree for the web page being updated not the DOM standard.
In this case maybe we could talk about the update of the way the interpretor uses innerHTML in order to make it sort of DOM compatible, but not about the "DOM update", because innerHTML is not part of the DOM. That HoboScript's phrase was ambiguous...:)

felgall
09-18-2008, 05:08 PM
In this case maybe we could talk about the update of the way the interpretor uses innerHTML in order to make it sort of DOM compatible, but not about the "DOM update", because innerHTML is not part of the DOM. That HoboScript's phrase was ambiguous...:)

Agreed.

Another thing that doesn't appear to have been mentioned in this thread yet is that (probably because innerHTML isn't a part of the standards) the implementation of innerHTML differs from one browser to another as to what you can actually use it for. Internet Explorer (which implemented it first) allows it to be used in far fewer situations than other browser allow. It can't update the content of a <tr> tag for example in IE while it can in other browsers.

Kor
09-20-2008, 02:30 AM
I always thought that innerHTML is based on a generous scope: to give javascript a simple and efficient method of inserting new elements, same as all the server-side languages have (for instance echo in PHP).

So far so good, but I guess that the major inconvenience in implementing this method in javascript is in touch of the initial ambiguous nature of the HTML language (content AND presentation). The moment when the separation between content and presentation will be complete (HTML=content, CSS=presentation), innerHTML could be implemented very easily as DOM, I hope.

I feel that an element written as <tag id="" class=""> could be better handled than the classical HTML <tag HTML_attribute1="" HTML_attribute2="" HTML_attribute2="" ...> so this must the reason for XHTML goes towards such a simplified approach.

felgall
09-20-2008, 04:48 PM
so this must the reason for XHTML goes towards such a simplified approach.

You can't use innerHTML with XHTML at all since the XHTML DOM requires that you also identify the namespace and innerHTML has no provision for supplying the namespace parameter which could of course be different for each element being inserted.

Using createElementNS(), deleteChildNS() etc is the only way to update pages using XHTML and so that gives another benefit to using the DOM commands for HTML since the code is easier to convert given that it is just a matter of replacing createElement(tag) with createElementNS(tag,namespace) etc throughout your code to switch from HTML to XHTML.