Creating a div element in jQuery

This question already has an answer here:

  • jQuery document.createElement equivalent? 13 answers

  • You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

    $('#parent').append('<div>hello</div>');    
    // or
    $('<div>hello</div>').appendTo('#parent');
    

    Alternatively, you can use the .html() or .add() as mentioned in a different answer.


    As of jQuery 1.4 you can pass attributes to a self-closed element like so:

    jQuery('<div/>', {
        id: 'foo',
        href: 'http://google.com',
        title: 'Become a Googler',
        rel: 'external',
        text: 'Go to Google!'
    }).appendTo('#mySelector');
    

    Here it is in the Docs

    Examples can be found at jQuery 1.4 Released: The 15 New Features you Must Know .


    Technically $('<div></div>') will 'create' a div element (or more specifically a DIV DOM element) but wont add it to your HTML document. You will then need to use that in combination with the other answers to actually do anything useful with it (such as using the append() method or such like).

    The manipulation documentation gives you all the various options on how to add new elements.

    链接地址: http://www.djcxy.com/p/2364.html

    上一篇: 当div变得可见时,jQuery事件触发动作

    下一篇: 在jQuery中创建一个div元素