jQuery document.createElement equivalent?

后端 未结 14 1694
暖寄归人
暖寄归人 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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 $("

    "), 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).

提交回复
热议问题