What is the most efficient way to create HTML elements using jQuery?

后端 未结 12 2464
甜味超标
甜味超标 2020-11-22 06:40

Recently I\'ve been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelming

相关标签:
12条回答
  • 2020-11-22 07:04

    If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!

    0 讨论(0)
  • 2020-11-22 07:05

    I use $(document.createElement('div')); Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.

    You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.

    0 讨论(0)
  • 2020-11-22 07:10

    I am using jquery.min v2.0.3 . It's for me better to use following:

    var select = jQuery("#selecter");
    jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);
    

    as following:

    var select = jQuery("#selecter");
    jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);
    

    Processing time of first code is much lower than second code.

    0 讨论(0)
  • 2020-11-22 07:11

    You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.

    0 讨论(0)
  • 2020-11-22 07:13

    I think you're using the best method, though you could optimize it to:

     $("<div/>");
    
    0 讨论(0)
  • 2020-11-22 07:16

    Question:

    What is the most efficient way to create HTML elements using jQuery?

    Answer:

    Since it's about jQuery then I think it's better to use this (clean) approach (you are using)

    $('<div/>', {
        'id':'myDiv',
        'class':'myClass',
        'text':'Text Only',
    }).on('click', function(){
        alert(this.id); // myDiv
    }).appendTo('body');
    

    DEMO.

    This way, you can even use event handlers for the specific element like

    $('<div/>', {
        'id':'myDiv',
        'class':'myClass',
        'style':'cursor:pointer;font-weight:bold;',
        'html':'<span>For HTML</span>',
        'click':function(){ alert(this.id) },
        'mouseenter':function(){ $(this).css('color', 'red'); },
        'mouseleave':function(){ $(this).css('color', 'black'); }
    }).appendTo('body');
    

    DEMO.

    But when you are dealing with lots of dynamic elements, you should avoid adding event handlers in particular element, instead, you should use a delegated event handler, like

    $(document).on('click', '.myClass', function(){
        alert(this.innerHTML);
    });
    
    var i=1;
    for(;i<=200;i++){
        $('<div/>', {
            'class':'myClass',
            'html':'<span>Element'+i+'</span>'
        }).appendTo('body');
    }
    

    DEMO.

    So, if you create and append hundreds of elements with same class, i.e. (myClass) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.

    Update : Since we can use following approach to create a dynamic element

    $('<input/>', {
        'type': 'Text',
        'value':'Some Text',
        'size': '30'
    }).appendTo("body");
    

    But the size attribute can't be set using this approach using jQuery-1.8.0 or later and here is an old bug report, look at this example using jQuery-1.7.2 which shows that size attribute is set to 30 using above example but using same approach we can't set size attribute using jQuery-1.8.3, here is a non-working fiddle. So, to set the size attribute, we can use following approach

    $('<input/>', {
        'type': 'Text',
        'value':'Some Text',
        attr: { size: "30" }
    }).appendTo("body");
    

    Or this one

    $('<input/>', {
        'type': 'Text',
        'value':'Some Text',
        prop: { size: "30" }
    }).appendTo("body");
    

    We can pass attr/prop as a child object but it works in jQuery-1.8.0 and later versions check this example but it won't work in jQuery-1.7.2 or earlier (not tested in all earlier versions).

    BTW, taken from jQuery bug report

    There are several solutions. The first is to not use it at all, since it doesn't save you any space and this improves the clarity of the code:

    They advised to use following approach (works in earlier ones as well, tested in 1.6.4)

    $('<input/>')
    .attr( { type:'text', size:50, autofocus:1 } )
    .val("Some text").appendTo("body");
    

    So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S) instead of 'size' then it will just work fine, even in version-2.0.2

    $('<input>', {
        'type' : 'text',
        'Size' : '50', // size won't work
        'autofocus' : 'true'
    }).appendTo('body');
    

    Also read about prop, because there is a difference, Attributes vs. Properties, it varies through versions.

    0 讨论(0)
提交回复
热议问题