SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    question about appendChild

    Hello,

    I have a hard time figuring out how to use appendChild().

    Basically, what I do now is:

    Code:
    myDiv.innerHTML += someHtml;
    But instead, I would like to do:

    Code:
    myDiv.appendChild(someHtml);
    where myDiv is an element targeted with getElementById and someHtml, well, some html (paragraphs wrapped in a div).

    So far, I can't get appendChild() to work...

    Anyone can give me some advice?


  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,682
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by rhgiant View Post
    But instead, I would like to do:

    Code:
    myDiv.appendChild(someHtml);
    where myDiv is an element targeted with getElementById and someHtml, well, some html (paragraphs wrapped in a div).

    So far, I can't get appendChild() to work...
    appendChild works with elements, not text, even if that text represents HTML.

    Code javascript:
    p.appendChild(document.createTextNode('This is an example of some '));
    strong.appendChild(document.createTextNode('strongly marked'));
    p.appendChild(strong);
    p.appendChild(document.createTextNode(' and some '));
    em.appendChild(document.createTextNode('emphasised'));
    p.appendChild(em);
    p.appendChild(document.createTextNode(' text.'));

    For example, as a test page:

    HTML Code:
    <html>
    <head>
        <title>An appendChild example</title>
    </head>
    <body>
    <div id="content"></div>
    <script>
    var p, strong, em, div;
    
    p = document.createElement('p');
    strong = document.createElement('strong');
    em = document.createElement('em');
    
    p.appendChild(document.createTextNode('This is an example of some '));
    strong.appendChild(document.createTextNode('strongly marked'));
    p.appendChild(strong);
    p.appendChild(document.createTextNode(' and some '));
    em.appendChild(document.createTextNode('emphasised'));
    p.appendChild(em);
    p.appendChild(document.createTextNode(' text.'));
    
    div = document.getElementById('content');
    div.appendChild(p);
    </script>
    </body>
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •