jquery append new div

21,079

Solution 1

That's because append() returns the original jQuery object (the one containing the <body> element), not a new one containing the appended content.

You can use appendTo() instead:

$('<div id="object">').appendTo('body').html(html).css({
    'top': '200px',
    'left': '300px',
    'z-index': '10'
});

Solution 2

$('<div/>',{
  id: 'object'
}).appendTo('body')
  .html(html)
  .css({
     'top': '200px',
     'left': '300px',
     'z-index': '10'
});
Share:
21,079
fish man
Author by

fish man

A fish, crying in the water...

Updated on August 15, 2020

Comments

  • fish man
    fish man over 3 years

    I want do hover in a div, append a new div in body part, some code here.

    but my problem is: now it is not append a new div but replace the first all html. Where is the problem? Thanks. http://jsfiddle.net/U7QqB/3/

    JS

    jQuery(document).ready(function() {
      $('.click').hover(function(){
        var html = $(this).find('.text').html();   
        $('body').append('<div id="object"/>').html(html).css({'top':'200px','left':'300px','z-index':'10'});
      });
    });
    

    css

    .click{position:realavite;top:100px;left:300px;}
    .text{display:none;}
    .object{position:absolute;}
    

    html

    <body>
    <h1>A hover append div text</h1>
    <div class="click">
        <img src="http://nt3.ggpht.com/news/tbn/U7Q-7enFr00rUM/1.jpg" />
        <div class="text">text</div>
    </div>
    </body>