I have HTML page with some HTML element with ID="logo". I need to create JS script (with no external libs calls) that will overwrite that html element with other HTML element like "<div id=logo> stuff inside </div>".
I have HTML page with some HTML element with ID=logo . I need to
Share
Most of the time, it’s just the content you want to replace, not the element itself. If you actually replace the element, you’ll find that event handlers attached to it are no longer attached (because they were attached to the old one).
Replacing its content
Replacing the element’s content is easy:
The
innerHTMLproperty has only recently been standardized, but is supported by all major browsers (probably most minor ones, too). (See notes below aboutinnerHTMLand alternatives.)Replacing the element iself
Actually replacing the element itself is a little harder, but not much:
Notes on
innerHTMLand other DOM manipulation techiquesThere are a number of wrinkles around using
innerHTMLin certain browsers, mostly around tables and forms. If you can possibly use a library like jQuery, Prototype, etc., I’d do so, as they’ve got workarounds for those issues built-in.Alternatively, you can use the various other DOM methods rather than
innerHTML(the same ones I used for creating the div and adding/removing, above). Note that in most browsers, doing any significant amount of markup by doing a bunch ofcreateElement,appendChild, etc., calls rather than usinginnerHTMLwill be dramatically slower. Parsing HTML into their internal structures and displaying it is fundamentally what browsers do, and so they’re highly optimized to do that. When you go through the DOM interface, you’re going through a layer built on top of their internal structures and not getting the advantage of their optimizations. Sometimes you have to do it that way, but mostly,innerHTMLis your friend.