简体   繁体   中英

Javascript: Changing innerHTML vs display

I'm developing a web form, where I want different inputs to appear depending on what the user previously selects. So I was wondering what's the difference between having an empty div and changing what it contains with innerHTML vs. having several div elements, setting the display to none, and changing which to show up depending on the user input.

Thanks!

Generally you should touch innerHTML as little as possible instead working with javascript commands like createElement and appendChild.

A lot of innerHTML manipulation is comsidered somewhat of an anti-pattern in javascript.

That said, if you have a single form or 2-3 forms you go ahead and do what works for you. Meaning what you see as easier to understand and more maintainable code.

At those scales I doubt anyone would notice the performance gain/defecit by using either approach. Personally I'd probably set the display to none.

It is almost always far more efficient to hide and show elements as required, rather than creating them and then destroying them.

This is principally because adding nodes to the document is a computationally expensive operation, even though innerHTML is highly optimised. Secondarily, it is because destroying elements also means you destroy any event handlers stored on those elements, which means you have to rebind them, which naturally takes time and unnecessary code.

Another advantage is that Javascript won't work if the user has disabled it or is using a browser that doesn't support it, eg a screen reader. If all your elements are present in your original HTML, the page will at least make some sense to these users.

If you have your div ready, simply change the display :

  • the code is simpler
  • you have only one storage place for your content (the divs)
  • the dom doesn't have to be recomputed by the engine

That's the standard solution when dealing for example with tabs.

If you change the elements with innerHTML , then when the form is submitted ONLY the inputs that are shown will be submitted.

By hiding elements with display , they are still present in the form and will still be submitted.

it will be faster if you are selecting divs by classes and ids and turning them on and off. However i would just use innerHTML if its just simple text because you wont notice the speed difference. Unless there is a reason to have different divs IE the selections have drastically different contents ie maybe a graph vs text vs table then i would make different divs.

in short they both do the same thing though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM