appendChild() into P fails, but into DIV succeeds. why..?

Discussion in 'JavaScript' started by beginner1, Aug 30, 2008.

  1. #1
    Hi All,

    I just have a strange situation, that I am failing on appending element into <p>.
    Following code will show what happens.

    I expected the target to be

    <p id="target_p"><div id="div_1">This is the 1st div.</div><div id="div_2">This is the 2nd div.</div></p>

    but, the actual result was

    <p id="target_p"><div id="div_2">This is the 2nd div.</div></p><div id="div_1">This is the 1st div.</div><p></p>

    according to the alert. Following is the one.

    ---
    <body>
    <script language="JavaScript">

    function f1()
    {
    // clone <div>.
    var element_div2 = div_1.cloneNode(false);
    element_div2.id = "div_2";
    element_div2.innerHTML = "This is the 2nd div.";

    // append ( only to fail )
    target_p.appendChild( element_div2 );

    // see what is happenning.
    alert(target_p.innerHTML);
    alert(document.body.innerHTML);
    }

    </script>

    <input type="button" onClick="f1()" value="Click to append" />

    <p id="target_p"><div id="div_1">This is the 1st div.</div></p>

    </body>
    ---


    But..

    If I stop using <p>, and try appending the same element into <div>, it works.

    I mean, deleting
    <p id="target_p"><div id="div_1">This is the 1st div.</div></p>
    and replacing it with
    <div id="target_p"><div id="div_1">This is the 1st div.</div></div>

    result was
    <div id="target_p"><div id="div_1">This is the 1st div.</div><div id="div_2">This is the 2nd div.</div></div>
    that I just expected.


    I have these questions that I cannot understand...
    (1) Why do I fail appending into <p> ?
    (2) Why do I succeed appending into <div> ?

    :confused:

    Anyone who helps me I appreciate so much.
    Thanks in advance.
     
    beginner1, Aug 30, 2008 IP
  2. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can't put a DIV in a P element, its invalid markup.
     
    MMJ, Sep 1, 2008 IP