user2483724
user2483724

Reputation: 2119

Nested element creation not working?

Trying to create an element within an element. Here it is an img within an anchor tag. I'm using append child but the "userLogoElement" when logged out is just the img tag and anchor is an empty anchor tag. Why isn't anything happening?

         var anchor  = document.createElement('a');
         anchor.href = var0;

         //---- Create image element ----
         var img   = document.createElement('img');
         img.src   = var1;
         img.title = var2;

         //---- Combine elements ----
         var userLogoElement = anchor.appendChild(img);

         console.log(userLogoElement, anchor, img);
         //console says img === userLogoElement, anchor is empty

Upvotes: 1

Views: 71

Answers (3)

Don Barry
Don Barry

Reputation: 86

I ran the following code :

<script type="text/javascript">
var0="www.google.com";
var1="bee.jpg";
var2="Don Bee";
    var anchor  = document.createElement('a');
     anchor.href = var0;

     //---- Create image element ----
     var img   = document.createElement('img');
     img.src   = var1;
     img.title = var2;

     //---- Combine elements ----
     var userLogoElement = anchor.appendChild(img);

     console.log(userLogoElement);
     console.log ("next");
     console.log(anchor);
     console.log("next");
     console.log(img);

     </script>

I have the following output

userLogoElement : img src="bee.jpg" title="Don Bee"

anchor :
a href="www.google.com" img src="bee.jpg" title="Don Bee" /a

this seems like it works fine. The returned value for userLogoElement is not your anchor

Upvotes: 1

Pranay Soni
Pranay Soni

Reputation: 1066

in jquery short coding style

$("<a>")
.attr('href','www.pranaysonisoft.blogspot.com')
.append($('<img>').attr('src','sdf.jpg'));

Upvotes: 0

MrCode
MrCode

Reputation: 64526

The code works fine http://jsfiddle.net/gcamP/

Be aware Node.appendChild() returns a reference to the node that was appended, not the node that you appended to. This is why userLogoElement is the image not the anchor.

Also note: in Firebug the log only shows the parent anchor, it doesn't include its children in the console log. Chrome on the other hand does show it. An easy way to test is to append it to the document and see for yourself (like in the fiddle).

Upvotes: 1

Related Questions