What's wrong with innerHTML?

I know Jeremy Keith's position on this but I still don't understand why him and others are so against innerHTML. Sure it's not part of a standard (yet) but neither is the XMLHttpRequest object (yet).

When you have something that is faster and easier, why wouldn't you use it?

Some have argued that it creates the potential for generating invalid markup but no more or less than creating invalid markup to begin with.

Is there some other reason for it?

Update Jeremy has clarified that he's not against it, but rather that it is "fast, easy, proprietary and heavy-handed".

Published April 13, 2006 · Updated September 14, 2006
Categorized as JavaScript
Short URL: https://snook.ca/s/575


64 Comments · RSS feed
Ryan Campbell said on April 14, 2006

I have some good insight on this issue because I have been wroking very closely with it for the past 6 months. When building a page that changed the DOM very frequently (so that it works like a desktop app) I found that the ONLY solution is innerHTML.

I built the app first by using proper DOM construction with document.createElement. The results were too slow in all browsers. So, I quickly changed to innerHTML to run some benchmarks. It was like a new app.

Basically, in real world examples proper element constructions is only an option for very simple construction. I would like someone preaching that innerHTML is bad to provide some examples of how they can make a modern app work efficiently without it.

Jon said on April 14, 2006

Personally, I'm sick and tired of all the valid markup preachers. It's just a bunch of whiners trying to fool themselves and others that their job is more important than it really is. see here

Dustin Diaz said on April 14, 2006

I'm here with you Jonathan. And it was only sometime in the last few months that Jeremy changed his mind. Just last December Jeremy posted his feelings on his love hate relationship for innerHTML. I too am on the fence for innerHTML. If you think about the practical existence of it in browsers... it's probably even better supported than DOM methods. innerHTML has been around longer. And doesn't help when mozilla goes ahead and gives innerHTML support to XML documents (shouldn't they call it innerXML?)

I find it extreamly useful when getting callback strings and dumping it into a div element. I mean who really wants to parse it out and build a DOM construct then append it to the document.

Anyway, I feel that Jeremy is only taking this postiion due to his "Task Force" role he has to play. I mean really, you have to admit the practicality of innerHTML.

Jonathan Fenocchi said on April 14, 2006

I try to avoid using innerHTML because I know it's considered bad practice and non-standardized (albeit widely compatible) code. In cases where I am updating exclusively text (but not HTML), I use the data property of an element, but if I need to output HTML via JavaScript, innerHTML is the fastest and easiest way to go. Creating nodes and text nodes with the DOM and then appending them to an element is a major hassle, and not worth the trouble, in my opinion. The only browsers that support the method fully also support innerHTML anyway.

Another factor is the way innerHTML outputs data. If you create a text node with HTML in it (say you're getting data from a PHP script that converts UBBC to HTML), JavaScript gets confused and throws an error; if you take that same output and use innerHTML, though, it will be output as expected. This is extremely important, as it would require an enormous amount of work to search for the HTML and create separate nodes via the DOM that contain the text nodes located therein. In short, it's a mess and beyond inefficient. InnerHTML is by a large margin the most efficient tool at our disposal, so we should use it, and it should be standardized.

Face it: just because it's not standardized doesn't mean it shouldn't be.

Kanashii said on April 14, 2006

I think it's mainly to point out that the DOM is not only used for HTML and that if you were to use any other language to manipulate documents you can't use innerHTML. Besides, the book is about the DOM, innerHTML isn't apart of the DOM API :D

Kanashii said on April 14, 2006

Scratch that comment about the book, I should pay more attention (currently reading the book) : )

Marco said on April 14, 2006

I'm all in favor of using InnerHTML as well. It works in all browsers, it's faster and it's often much less complicated in terms of code.

Me using InnerHTML could be seen as a part of the almost valid xhtml philosophy I adopted quite a while ago.

The whole standards nazi thing is crap. Cross-browser CSS design, unobtrusive Javascript, degradability etc. etc.: great! But when a site has all this, works in all modern browsers and the client is happy then who gives a flying *beep* about using InnerHTML or some ultra-minor validation problems? I for one don't. Not anymore.

hukl said on April 14, 2006

I consider myself as a standard nazi. (and i'm german and i live in berlin haha ....)

why ? because i left the webdesignbusiness for a couple of years because of the lack of standards, because every browser did what they thought should do. nothing worked nowhere except on your favourite browser. It was no fun at all so I quit it and went for print and photography. A year ago or so a friend of mine told me to check out the web again since so many things have changed. I was glad to see that CSS finally worked as it was supposed to, I also liked XHTML 1.0 strict because it forced you to seperate the content from the design - i liked the whole thing - why ? because standards where there !

For how long have you all been crying for them huh ? Same thing with JScript, Javascript and Ecmascript. How often have you blamed Microsoft for not going along with the standards ? How angry do you get when something that is in the standards doesn't work for you ? I know, as long as it makes your live easier you're losing the standards way pretty fast. In my opinion it shouldn't even be Web 2.0 - it all feels more like Web 1.5 ... on a good way but still a couple of miles to go.

Don't get me wrong here - I don't really blame you for considering innerHTML the better choice. It may is, it may will find its way in the dom spec and then it is all good - also for me ;)

Really I was a little too harsh to make my point in the first part but I really feel strong about standards - i was happy to see that they finally got widely implemented and I can't see why people would go out and say "who needs the standard way anyway" since we ALL were waiting so long for it. It was just the tone of some of the comments that kind of made me angry!

It sounds much better to say "i have a valid xhtml 1.0 website with valid css 2.1 and i'm using the dom api to manipulate it" this gives you a perfect definite idea about a site wherelse "yeah i have a page that is not valid xhtml, with some css hacks and some IE javascript functions" gives you a whole other feeling right ? ;)

When I met Bert Bos, the guy who made CSS, he said "people always want cool new features - what they don't want is to write the specs"

So I'm not sure if I made any points here - except for that I feel kinda strong about standards - but I just got up ;)

And I think people who are using innerHTML are still cool - in my eyes just a little less than the ones who don't ;)

Jeremy Keith said on April 14, 2006

Jonathan, don't oversimplify things by claiming to know my feelings on innerHTML from a single posting on the DOM Scripting Task Force blog.

For balance, here's something else I wrote on the subject:


Please don't paint such a black and white picture of me being "against" innerHTML unless I actually say "I am against innerHTML". Thanks.

Please read what I actually wrote and don't misrepresent me so blatantly. I said innerHTML was proprietary. I didn't use words like "wrong" or "bad".

Dustin... the same.

Jonathan Snook said on April 14, 2006

Jeremy: I've read that post and the one I've linked to in the article. You've called it "heavy-handed" and a "sledgehammer" (during your SXSW presentation). Every time you've talked about it has been with a negative spin. I think it's easy to see why I might think you might be against it.

I suppose where I went wrong is using the word 'against'. As it probably came across as if you were saying "NEVER USE innerHTML". Which isn't what I meant. I meant, "why are there people who have to be negative when talking about innerHTML?"

So, likewise, don't paint my words as being so black and white.

Jeremy Keith said on April 14, 2006

Jonathan, at the very same SXSW presentation you mention, I stated that innerHTML is much quicker than using DOM methods.

Yes, I use words like "heavy-handed" and "sledgehammer" to describe innerHTML because I think they accurately describe it. That doesn't mean it's bad. They are accurate words. If you have something against sledgehammers, they might sound negative but what I'm striving for is accuracy.

innerHTML is fast, easy, proprietary and heavy-handed.

DOM methods are slower, long-winded, standardised and precise.

Now, which technology have I described with a negative spin and which technology have I described with a positive spin?

The answer to that question is entirely subjective and depends on where your particular priorities lie.

Eden Jaeger said on April 14, 2006

Both innerHTML and XMLHttpRequest are proprietary so I don't see what the big discussion is all about. Are we validating our JavaScript with the W3C now? They are both widely supported and there is no reason to believe that innerHTML may not receive the all important STANDARDS BLESSING some day. Use the one that makes the most sense for your application. Doing *that* will earn you *my* Standards Blessing and you'll probably feel better about your app at the end of the day. Fair enough?

Veracon said on April 14, 2006

Because it's totally inflexible. DOM allows for changing of things without having to completely reload content; this greatly both simplifies and empowers coding.

Johan said on April 14, 2006

Seems obvious but:

From this article I got: http://slayeroffice.com/articles/innerHTML_alternatives/#intro

> It was when my favelets stopped working for people when they were invoked on application/xhtml+xml sites that I decided to wash my hands of it (and do a lot of re-coding).
> Since it's not a standard, it isn't terribly future proof. It's not supposed to work under the application/xhtml+xml MIME type that XHTML documents are supposed to be served under. (Firefox 1.5 changed this by allowing it for some reason)
># innerHTML is a string. The DOM is not a string, it's a hierarchal object structure. Shoving a string into an object is impure and similar to wrapping a spaghetti noodle around an orange and calling it lunch.
# It makes for some nearly illegible code in a lot of instances, with escaped quotes and plus signs all over the place appending data to the string, which in my opinion makes it difficult to maintain.

Johan said on April 14, 2006

on the + side

># It's less verbose than DOM methods.
># It allows you to take arbitrary chunks of markup and drop them into a document without having to parse them.

you see!

Andrew Dupont said on April 14, 2006

There are situations when an HTML document is best represented as a complex tree structure. There are also situations where an HTML document is best represented as a linear stream of markup.

I love the DOM, but it's one of many different APIs for navigating a page, and it's not always the best. The fact that it's the only standard we have is unfortunate, but I'm not going to use the wrong tool for the job just because the better tool isn't as fondly-regarded.

Mark Wubben said on April 14, 2006

Well, innerHTML has better browser support (in HTML pages). It also does not create invalid markup because the browser will make sure the output forms a valid DOM. In fact, it could be argued that the DOM methods let you create invalid markup.

As far as I know, the reason innerHTML will now work in XML pages is because it is being specified in the WHAT WG specs.

Eden, XMLHttpRequest is being specified by the W3C, see http://www.w3.org/TR/XMLHttpRequest/.

Finally, innerHTML is quite a handy trick to force Safari into repainting (a part of) the document.

JAbbott said on April 14, 2006

I'm with Jonathon (not that taking sides is necessary!). While I enjoyed Jeremy Keith's SXSW presentation, the message was a little confusing. After recently beginning to use and appreciate innerHTML, the presentation led me to believe that it was the wrong way to go. Then one of the comments during Q&A was that the "right" way to do it was slow and not practical except in small doses.

Dustin Diaz said on April 14, 2006

Jeremy, also in the same presentation at SxSW, you can just hear it in your voice ;) It came off sounding bad like "never use innerHTML" and yea, sure you didn't say it... but c'mon now... I definitely got the impression. Don't forget the power of human interpretation. I am almost positive the rest of the crowd got the same feeling when you were comparing innerHTML versus DOM methods.

Anyway, aside from the matter, we'll discuss this matter a bit more at a bar in London ;)

Stuart Langridge said on April 14, 2006

Mark: the browser won't necessarily make sure that the output from innerHTML forms a valid DOM. It'll do whatever it does when confronted with that HTML in an ordinary page. IE certainly used to form an invalid DOM when presented with invalid HTML, and that's not changed as far as I'm aware?

Adam Liptrot said on April 14, 2006

Without getting into what everyone thinks Jeremy feels about innerHTML, here's my twopenneth. If you know that your code is only going to be accessed as HTML then I think innerHTML is a valid tool in certain circumstances. In fact I've just used it myself to write a block of HTML to an ActiveX object. In that example I had no reason to insert each node seperately, doubly so as I had no advance notice of what the HTML would be. innerHTML performs admirably in this instance. Elsewhere I have used the full power of DOM and been grateful for it.
Yes, inner HTML might not be valid and may never be part of the spec, but it is supported by the majority of browsers. We aren't talking blink tags here. Appropriate tool for each job I say, if it warrants a sledgehammer then I'll use it.

Stuart Colville said on April 14, 2006

Whether to use innerHTML or the DOM really comes down to application and speed is definitely going to be a consideration.

I am also pretty sure that a lot of developers use innerHTML more out of laziness because they can't be bothered to write the code to build up the nodes required to insert a chunk of HTML via the DOM.

Mark Wubben said on April 15, 2006

Stuart, apologies, I had forgotten to calculate IE into the equation. MOSe browsers should work as described though.

Danny said on April 15, 2006

I've a feeling innerHTML, with a little tweaking, could be made a lot more reliable in regards to producing valid markup. It would be nice to see this going in a spec somewhere - I'm not sure about some of their other bits, but it sounds like the WHAT WG seem to be getting things right here. There's no denying straight DOM methods can be tedious to work with.

The whole idea of having good specs as standards is to enable working code. Validation against the specs takes a lot of the weight of the individual app developer. Some testing against various target clients (which might not be traditional browsers) is always going to be necessary, but the chances of success are greatly increased when everyone's reading from the same book.

Sébastien Guillon said on April 15, 2006

The problem with innerHTML as it appears is that it allows authors to input potentially invalid or ill-formed code into a document which is, ideally, well-formed and valid.

Then I'm wondering if it's at all possible (and practical for all UAs and in a reasonable timeframe) to have a standardized version of innerHTML that would check the well-formedness of the input code and, possibly, its validity in regard to the DOCTYPE of the document.
If the code is rejected, false is returned and nothing happens. It could even be optional wether you want it valid+well-formed, just well-formed, or if you accept any kind of crap.

Call me a Candide, but I'm really wondering. Any gurus have an answer?

noiv said on April 15, 2006

I think this discussion is academic. It is possible to write a parser in JS, which accepts XML like "<div><br /></div>" as argument and alters given node in an appropiate way. As prototyped function called 'innerHTML' you could use it like:

document.innerHTML("<div><br / ></div>")

Is it bad or good? Anyway it is slower than Browsers implementation of innerHTML. For Browsers without innerHTML I would code this parser, because HTML is more eyefriendly structured than:

var d = document;

Matthew McLeod said on April 17, 2006

whoa. Everyone seems rather polar about this.

My take -

a) proprietry techniques are part of the reality of web development, we cater to 'proprietry' flaws all the time, why not take some of the good?

b) Regardless, I still prefer the DOM approach. You're all supposed to be transfoming your XMLHttpRequest responses with some nice XSL right? Or are you using JSON? (Wait, that's not standardised either).

c) tool:task.

d) http://www-128.ibm.com/developerworks/xml/library/x-matters41.html#N10115 etc. A good developer doesn't spend time complaining about his tools - he makes it work, and does it as best he can.

James said on April 19, 2006

This post a comment box is cool

troels said on April 19, 2006

I like to think that they are two different tools, which you use for different tasks.
The choice between innerHTML and DOM depends on the input. If you have a snippet of markup, which you want interpreted and insert into the document, I see absolutely no other sane choice than innerHTML.
On the other hand, getting a chunk of html-markup over the wire (From XmlHttpRequest most likely) is wrong in the first place. Why ? because HTML is view-data, and you should have transmitted model-data and left it for the client to transform that into view.
If you do the transformation programmatical, DOM would be most appropriate.
Then again, if for example, you use XSLT to generate the view, you'll end up with a chunk of markup, which ofcourse you'll insert through innerHTML.

Fernando Lucas said on April 19, 2006

I use innerHTML cause it's the one I remember the fastest. Being new to DOM scripting and all. But I've been told several times to use childNodes[x].nodeValue instead (or first/lastNode.nodeValue).

I think it works the same, doesn't it?

tom said on April 20, 2006

My main aversion to using InnerHTML is the alteration of the markup code that IE makes. It really frustrates me that IE actively changes the code when using InnerHTML to assign content to a node.

To demonstrate this, try this bit of code:

var div = document.createElement("div")
div.innerHTML = '<' + 'a href="test.html">test<' + '/a>'
// i had to break up the a tag so the comment rendering system wouldn't treat it as a real link ;-) not really required!
alert('InnerHTML: ' + div.innerHTML);

div = document.createElement("div")
var a = document.createElement("a")
a.setAttribute("href", "test.html")
alert('DOM: ' + div.innerHTML);

If you run that in Firefox, you'll see that the code is entered exactly as desired, however in IE with InnerHTML it prepends the URL of the site to the href of the A tag. This can get very frustrating when, for example, using InnerHTML in a Content Management System that resides in a subdirectory of a site, yet is controlling content on the front page of the site. So a simple href to "test.html" would become "admin/test.html" (if the CMS is in admin/).


said on April 21, 2006

Tom, IE might be changing the innerHTML when you request it, that is, it might be correct in the DOM but not in the returned string.

tom said on April 21, 2006

If it was correct in the DOM but not the returned string the second alert (where I set the content through the DOM) would be the same as the first.

tom said on April 21, 2006

In my earlier post this line:

div.innerHTML = 'test'

Should read

div.innerHTML = '[a href="test.html"]test[/a]'

(although I've used real tags in my code, not square brackets).

Pasting tags into comments was.. erratic. :-)

said on April 21, 2006

Oops, looks like the caffeine hadn't kicked in yet.

Steve Griffith said on April 22, 2006

The approach that I have used when discussing the difference in usage for innerHTML and DOM with my students has been to treat innerHTML as an excellent way to append text to elements on their web pages.

Using the createElement, createAttribute, and appendChild methods reminds them to keep well-formed, valid xHTML in mind at all times.

I have seen issues with innerHTML not rendering attributes properly. This is avoided with the DOM methods.

I am a vocal supporter of standards. I've been stuck having to clean up the messes of other developers who did the bare minimum to make a page work in their personal favourite browser too many times.

So, I refuse to let my students get away with using markup or methods in their scripts that lead to a lack of appreciation for how standards have helped to clean up the mess that used to be the web.

Now, having said that, I realize that both approaches are attempts to solve a problem and neither one is the defacto standard. So, both are still acceptable on some level. innerHTML works effeciently and if left to the role of appending text to existing or newly created elements then that's great.

If, however, you want to alter the structure of a page, then use the methods that allow you to explicitly do so. We've moved on to xHTML so that paragraphs have to have a closing tag and it is not left up to the interpretation of the browser. Why not follow the same logic in our scripts? Tell the browsers exactly what elements to create and tell them exactly where to stick 'em...

Rick said on April 22, 2006

Simplicity rules. I use innerHTML, as it seems faster and far quicker to code. Just like sometimes, I use XMLHttpRequest to fetch text rather than XML. Why parse or manipulate DOM if you don't absolutely have to?

After all, its a means to an end - that is, updating content.

Sam said on April 23, 2006

There is a simple solution for those who use innerHTML because it's easier:

function ezAppend (element, string) {
tom said on April 24, 2006

Sam, that won't work if you want to have tags inside your string (createTextNode will escape the string)

Andrew Martinez said on April 25, 2006

I don’t like innerHTML because if you do it in IE, there is a lag between the time IE will update its representation of the DOM tree. Thus, if you set HTML via innerHTML and then immediately attempt to access the nodes, they will not be there. Slightly frustrating if you are interfacing with another script that uses innerHTML. If you are in FireFox, innerHTML, the injected HTML will be fully parsed before FireFox continues.

Panda said on April 26, 2006

Hi, I use innerHTML to create more space on the main page of blogspot. But when I move the Archives to another inner-page Blogger seems not able to track it down, i.e. no archives appear. Do you have any thoughts about this? Thanks a lot :) ^_____^

Ismael said on May 03, 2006

Welll...The DOM is used to parse HTML/XML to an objet structure so you can locate, extract and modify those objects. Very useful for that. If you just want to print some chunk of code to the page it is perfectly reasonable to use innerHTML. The browser will have to parse it internally anyway, so there's little point in parsing it yourself via DOM and then making the browser work twice since it will have to render your modified DOM.

it is a matter of purposes.

Rico said on May 03, 2006

Here's why I don't use innerHTML:

[div id="foo"]
[a id="foo-head" href="..."]A link[/a]

document.getElementById('foo-head').onclick = function()
{ alert("Hello."); return false; }
document.getElementById('foo').innerHTML += ' to [b]nowhere[/b].';

Once the foo DIV's innerHTML is modified, foo-head will be recreated, and the onclick property we set will be wiped out. Nothing will happen when the link is clicked.

Also, there's no easy way to reference the elements I put in with innerHTML. (e.g., if I wanted to put an onMouseOver event to the [b] in the example.)

Moh'd JB said on May 09, 2006

Hi , Love your discussion! here are my 2 cents, I've been using innerHTML for 8 months and DOM methods for more than 18 months, but now mostly innerHTML, the time when I need to use DOM createElement is for example, inserting an LI in a certain index in an UL/OL that that container has a lot of LI's , or you can imagine other similar cases when a container tag is filled with structured nodes and you don't want to rewrite the whole sub tree, but just at specific location, and then! the newly created and newly inserted tag i would AGAIN use innerHTML to fill the new born tag.
other cases when i use DOM ( and innerHTML is USELESS) is when i need firstChild/nextSibling, i.e. to traverse the tree for the sake of doing eye candy ,e.g.:
var x=findParent(evt.target?evt.target:evt.srcElement
/*function findParent would use parentNode+firstChild+nextSibling to get the job done: find the containg UL with certain conditions

having said that, each (i.e. DOM vs. innerHTML) has its own purpose, and i dont think that i would feel easy to choose one of the two, in other words, both are good, if you know that, each tool is for its purpose!

and as for standards, I agree with hukl, if you have been long enough in the arena , then you'll appreciete why standards are good, coz there were days when the yen and the yan were tooo diffrenet to tolerate to write a cross browser library-of-function!

it should not be innerHTML vs. DOM
and innerHTML vs. standards,
i'd love to see innerHTML and XMLHttpRequest subsetOf w3c something!

Moh'd JB said on May 14, 2006

hello again , this time i've got a question: in IE 6&7 i use xmlrpc in xmlhttp and the response would work 100%,i mean the response is fed into innerHTML of the srcElement, but in firefox the response string is truncated when the string is Very long, so feeding the response string (which is incomplete html fragment) would result in an unwant trashy page !
i've been trying to debug and trace why the response string is not complete, and for more than 10 days i still dont know why the string is truncated, please
please, if some one knows why this is happening in firefox1.5 and how to fix it, please inform me.
thank you!

hloworld said on May 20, 2006

I believe that your problem is related to Firefox's 4K limit on a node. Search for "split very long text nodes into multiple smaller text nodes" in the body of this link.


Hope this helps.

Kramer said on June 01, 2006

From the sound of things, innerHTML will BECOME a standard in short order. It's faster, easier to code for in many instances, and developers would definitely prefer it if it was already a standard.

It has all the properties of a standard by popular demand.

Therefore, I say, use it! It works well now, and is likely to be included in the next spec anyway.

And, Stuart Colville: I just wrote code to build an entire calendar using 100% DOM API valid code, and it's so dog-slow now that I have to rewrite it to use innerHTML. It's not laziness, I see that I have no other option!

staima said on June 16, 2006

I think Jon is right! innerHTML or document.write, they are tools, who cares if like them or use them? Look: server will crash any time you use document.write!!!

Paul said on July 09, 2006

Browsers need to get their act together and make DOM manipulation faster; rendering is complex. Tree manipulation is not.

staima said on August 24, 2006

I have to apologies for reposting on the same subject again, but English is not my first language and I have a lot of difficulties to express my ideas in the right way. I was not clear enough in my last post, so I will try again here:

There is a tendency among programmers to agonize and fret over things in programming. They go so far to define their personal LOVE or HATE to specific languages or tools inside a language. Those we call: Self-Appointed-Thought-Leaders or Gurus! Final goal for them is; to prove that one language or method is “morally bad”, so they need to plan, organize and execute a kind of “language revolution” to bring it down and exterminate it from public use... Yeah, it is that funny!

The only important thing for one language or method is: can we use it to achieve a goal...

Schwarzer said on November 10, 2006

Do you have any problems with the new versions of firefox 2.0 by using?

Jonathan Snook said on November 13, 2006

Schwarzer: I haven't seen nor heard any issues using innerHTML in firefox 2.0.

Anna said on January 23, 2007

Quick question for you all. Have any of you had issues when using innerHTML that IE produces a runtime error when encountering a FORM tag in the innerHTML to be rendered? I am having the worst time with this. Works great in FireFox but throws a wobbly in IE. If I take out the form tag the innerHTML renders fine.

Thanks in advance,

Keven said on April 04, 2007

Rico I'd have to agree with you, that is my same frusteration with innerHTML

I mean it's great if you just want to 'add something' to a node, but if you want to actually add something while keeping the current values, the current values disappear.

Ed Norton said on April 20, 2007

I'm a bit of a standards fanatic myself and I've been reading a lot about innerHTML. Here is the problem I have with not using it.

Say that you have a section of a page, a rather large section with many paragraphs and divisions and maybe a list.

Say that you want to take all of this and put in inside a new division, wrap a new division around a huge portion of the html.

To do this the standards way would require completely rebuilding the page, adding the required div and then putting everything back into it. With innerHTML I simply need to extract the current contents of the element in question, add the opening and closing div tags (concatenate them to the start and end of the string) and then set the innerHTML of the element in question to the new string.

The standard way of doing things does not sound like a realistic way to accomplish the goal. Especially when I have a deadline to meet. The non standard way will take me under a minute. The standard way could take days to program.

So, in some cases, even though I am a bit Obsessive Compulsive about standards I have to say that some of them are just unrealistic. HTML is a text document, the only thing that will be looking at my web pages is a browser. Why should I not treat it is as text?

Thomas Woodard said on May 03, 2007

XMLHttpRequest to DOM translation == innerHTML substitute (not as fast, of course): http://domaxh.sourceforge.net

Neil Craig said on May 07, 2007

There are some instances where one cannot use the DOM methods to alter the HTML. When the document is in 'designMode', one can only use the DOM to view the nodes and their respective values. One cannot use the DOM methods appendChild, removeChild, or replaceChild. The only way to alter the it is innerHTML;

Gary said on June 23, 2007

innerHTML is fast and small footprint. Just what web pages SHOULD be... whats the point of optimising the graphics, slicing up images to load faster, etc if you're then going to load the interface down with a whole load of longwinded garbage.

innerHTML is a simple and obvious way to replace elements in a page... note that we're not talking about arbitrary sections, but well defined sections... special container DIVs set up for the purpose of holding content. Just like loading and unloading Plugin DLLs in a binary app.

Now, yes, the result can be malformed HTML. But ONLY if you INJECT BAD HTML. This has nothing to do with the method of switching these blocks in and out of the page... but in creating them in the first instance. Create them properly, and only inject them into container tags, and this problem goes away. Get anal about it and you can argue that notepad produces malformed HTML, so does PHP and so does too much beer.

The ONLY real problems with innerHTML are...

- Nobody has bothered to standardise it, possibly because...
- Theres more industry revenue in more complex schemas
- In the absence of a standard the UA vendors are making a collective ass of themselves again.

So, yes... it wipes out javascripts dynamic handlers tied to an object if you append code to the div (sometimes)
Yes, you cannot add to an IE table (sometimes)
Yes, the newly written objects are not immediately available under IE (sometimes)

Thats why we need a standard! What we need to do is lock Bill's team and the Mozilla team in a room and refuse to let them out till they've agreed on the best way of handling, preserving and refreshing HTML when the structure is altered.

...and, just to assist them both to reach the best possible solution... Bills team should be gagged and handcuffed to their chairs.

In principle there is bugger all wrong with innerHTML for most purposes.


Gary said on June 23, 2007

... Oh, actually, while they're at it they could also standardise on a method of creating the XMLHttpRequest object. There should be a standard structure for instantiation of such objects with a formalised specification regardless of the modules implementation.

THESE are the real problems my friends. Asshat UAs trying to run the whole show and then pin inconsistencies on the competition (You listening Bill?)

(Sorry about the double-post)


mel said on July 23, 2007

innerHTML, I always run into problems with it. and javascript in general. but it is what is out there.

Michael Buckley said on September 05, 2007

I jump between the two all the time. Some times it is easier to use the proper DOM methods, these can also be much faster if you use the clone() function and avoid creating nodes, which is IMHO a very slow way of doing something.

But then there is also the cases where it is better to use innerHTML. I would bet that the preview feature that is copying out what I write below is using innerHTML. Could you imagine trying to get that to work with DOM methods? Like I can type a link like this MySite and it shows up. If you use DOM, I would have to first use regular expressions to find out the node name, then the attributes, then the text in it. That would be so painful, you would not do it.

Michael Buckley said on September 05, 2007

I jump between the two all the time. Some times it is easier to use the proper DOM methods, these can also be much faster if you use the clone() function and avoid creating nodes, which is IMHO a very slow way of doing something.

But then there is also the cases where it is better to use innerHTML. I would bet that the preview feature that is copying out what I write below is using innerHTML. Could you imagine trying to get that to work with DOM methods? Like I can type a link like this MySite and it shows up. If you use DOM, I would have to first use regular expressions to find out the node name, then the attributes, then the text in it. That would be so painful, you would not do it.

Roarmakag said on February 15, 2009

Я бы сказала о монументальности, грандиозности некоторых сюжетов. А назвала бы - "нефильтрованный реал". На мой взгляд, красота - это все-таки другое: лучшее, чистое, избранное, заставляющее трепетать и поражаться. Можно найти красоту во всем, но всё скопом - не есть красота. Имхо.

приколист said on February 18, 2011

Я никак не смогла вставить рисунок в коментарий. Вставляю ссылку на рисунок а он не показывает его как рисунок. Что мне делатЬ?
Фотки беру отсюда - images.yandex.ru/yandsearch?text=snook.ca

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.