What is better, appending new elements via DOM functions, or appending strings with HTML tags?

后端 未结 6 1134
无人共我
无人共我 2020-11-29 05:34

I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either

document.getElementById(\'foo\').innerHTM         


        
6条回答
  •  悲哀的现实
    2020-11-29 06:06

    There are a number of differences:

    1. innerHTML has only been standardised by the W3C for HTML 5; even though it has been a de facto standard for some time now across all popular browsers, technically in HTML 4 it's a vendor extension that standards-adherent developers would never be caught dead using. On the other hand, it's much more convenient and practically it's supported by all browsers.
    2. innerHTML replaces the current content of the element (it does not let you modify it). But again, you gain in convenience if you don't mind this limitation.
    3. innerHTML has been measured to be much faster (admittedly, that test involves older versions browsers that are not widely used today).
    4. innerHTML might represent a security risk (XSS) if it's set to a user-supplied value that has not been properly encoded (e.g. el.innerHTML = '
提交回复
热议问题