Quote:
Originally Posted by kduan
So I'm fairly new to javascript, and I've mostly been using .innerHTML to manipulate text and other HTML elements. However reading around, most people have a very unfavorable view on this method. So my question is: What do you guys use and why is it better? or Why is .innerHTML frowned upon?
|
There are a few situations where innerHTML doesn't work.
With Internet Explorer you can't use it to replace part of a table or select list. Also it doesn't update the Document Object Model in all browsers and so you can't use DOM methods to replace parts of conetent added that way.
Also innerHTML requires that the container you are adding the content into already be part of the page.
The only other disadvantages it has are that you need to enter < and > when supplying HTML tags as part of the innerHTML content and you can't use it to move parts of the page from one position in the page to another in a single command.
Given the much larger amount of code that using the standard DOM methods require to achieve the same end result there is little incentive for replacing innerHTML calls except where they don't work or where the alternative results in shorter or easier to read code.
innerHTML also has the benefit of being the simplest command for beginners to use for interacting with the web page from JavaScript without having to learn all of the DOM commands first.
The alternatives to innerHTML will involve calls to createElement and to one or more of appendChild, insertBefore, or replaceChild.