jQuery document.createElement equivalent?

后端 未结 14 1698
暖寄归人
暖寄归人 2020-11-22 05:41

I\'m refactoring some old JavaScript code and there\'s a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement(\"div\");
odv.style.di         


        
相关标签:
14条回答
  • 2020-11-22 06:23

    I've just made a small jQuery plugin for that: https://github.com/ern0/jquery.create

    It follows your syntax:

    var myDiv = $.create("div");
    

    DOM node ID can be specified as second parameter:

    var secondItem = $.create("div","item2");
    

    Is it serious? No. But this syntax is better than $("<div></div>"), and it's a very good value for that money.

    I'm a new jQuery user, switching from DOMAssistant, which has a similar function: http://www.domassistant.com/documentation/DOMAssistantContent-module.php

    My plugin is simpler, I think attrs and content is better to add by chaining methods:

    $("#container").append( $.create("div").addClass("box").html("Hello, world!") );
    

    Also, it's a good example for a simple jQuery-plugin (the 100th one).

    0 讨论(0)
  • 2020-11-22 06:25

    I'm doing like that:

    $('<div/>',{
        text: 'Div text',
        class: 'className'
    }).appendTo('#parentDiv');
    
    0 讨论(0)
提交回复
热议问题