SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru DeNasio's Avatar
    Join Date
    May 2001
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    x.innerHTML vs x.appendChild?

    Hello guys,

    I'm just learning about HTML DOM and have the following question.

    If you want to create something like: <a ...><img ...></a> with HTML DOM, then I believe you can do that in the following ways:

    1)
    var newA = document.createElement('a');
    newA.innerHTML = "<img...>";

    or

    2)
    var newA = document.createElement('a');
    var newI = document.createElement('img');
    newA.appendChild(newI);

    I believe both codes will work, right? Which one is better to use? Any advantages/disadvantages when using one or the other?
    Ballot-Box.net - free polls for webmasters
    FormLog.com - free form processor

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,813
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    The advantage of the second way is that it actually updates the DOM properly in all browsers so that you can actually read back and update the tags you added.

    Using innerHTML does not update the DOM in all browsers and so the content added that way may not be able to be updated after it is added (if you need to do that).
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •