Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If people recommend I shouldn't use .innerHTML, what then should I instead use? [duplicate]

Tags:

javascript

Possible Duplicate:
JavaScript: Is it better to use innerHTML or (lots of) createElement calls to add a complex div structure?

What should I use instead of .innerHTML? All advice is appreciated.

like image 759
David G Avatar asked Sep 19 '11 20:09

David G


People also ask

What can I use instead of innerHTML?

innerHTML = template; And if you want a more React/JSX-like approach, you can use template literals instead. Note: only works in modern browsers—you'd need to use Babel to transpile it. var app = document.

Should I never use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

Should I use innerHTML or innerText?

innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.

What is the disadvantage of using innerHTML?

There is no append support without reparsing the whole innerHTML. This makes changing innerHTML directly very slow. innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it.


2 Answers

The correct answer is that in certain situations you should use innerHTML, and in other situations you should use appendChild. Here's when to use innerHTML or appendChild:

  • Use innerHTML when you're setting text inside of an HTML tag like an anchor tag, paragraph tag, span, div, or textarea.

  • Use appendChild() If you're trying to add new DOM elements inside of another DOM element.

like image 76
Eric Rowell Avatar answered Oct 06 '22 23:10

Eric Rowell


You can use W3C compliant methods, like:

  • createElement()[docs]
  • appendChild()[docs]
  • removeChild()[docs]
  • replaceChild()[docs]
  • insertBefore()[docs]
  • createTextNode()[docs]
like image 33
user113716 Avatar answered Oct 06 '22 23:10

user113716