jQuery - Appending a div to body, the body is the object?

后端 未结 6 1749
無奈伤痛
無奈伤痛 2020-12-28 11:58

When I\'m adding a div to body, it\'s returning the body as the object and then whenever I use that - it\'s obviously using body. Bad.

Code:-

var hol         


        
相关标签:
6条回答
  • 2020-12-28 12:31

    jQuery methods returns the set they were applied on.

    Use .appendTo:

    var $div = $('<div />').appendTo('body');
    $div.attr('id', 'holdy');
    
    0 讨论(0)
  • 2020-12-28 12:33

    Using jQuery appendTo try this:

    var holdyDiv = $('<div></div>').attr('id', 'holdy');
    holdyDiv.appendTo('body');
    
    0 讨论(0)
  • 2020-12-28 12:33
    var $div = $('<div />').appendTo('body');
    $div.attr('id', 'holdy');
    
    0 讨论(0)
  • 2020-12-28 12:42
    $('</div>').attr('id', 'holdy').appendTo('body');
    
    0 讨论(0)
  • 2020-12-28 12:42

    Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

    var holdyDiv = $('<div />').appendTo('body');
    holdyDiv.attr('id', 'holdy');
    

    .appendTo() reference: http://api.jquery.com/appendTo/

    Alernatively you can try this also.

    $('<div />', { id: 'holdy' }).appendTo('body');
                   ^
                 (Here you can specify any attribute/value pair you want)
    
    0 讨论(0)
  • 2020-12-28 12:47
        $('body').append($('<div/>', {
            id: 'holdy' 
        }));
    
    0 讨论(0)
提交回复
热议问题