Create new elements to DOM JS vs Jquery

0

I am trying to optimize a code that is written in Javascript and other parts in Jquery. The question is simple, what is more efficient to create elements?

 $(function(){
    //OPCION 1
    $('#myDiv').append('<button id="myBtn">Jquery</button>');
    
    
    
    //OPCION 2
    let btn = document.createElement('button');
    btn.id = 'myBtn';
    let txt = document.createTextNode('Javascript');
    btn.appendChild(txt);
    document.getElementById('myDiv').appendChild(btn);
    
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
    </div>

Welcome comments

    
asked by Alberto Siurob 06.11.2017 в 16:42
source

2 answers

1

To begin with, we must remember that JQuery is nothing more than a library written in Javascript, so we can distinguish between using JQuery and not using it, but in both cases you use Javascript.

On the other hand, we should define what efficiency is and how much it affects:

If you are going to create and insert thousands of elements, do not use JQuery, because after all this library is a layer of abstractions on the DOM, which will affect performance.

If you want to insert a couple of dozens of elements, the gain in runtime will be milliseconds, or hundredths of a second in the best case. But at the time of writing the code the same takes half the time that using the DOM API natively, so the efficiency during the development time would make me inclined to use jQuery.

In summary: as almost always, everything depends and there is no absolute answer.

    
answered by 06.11.2017 в 16:56
0

It's always better to work with pure Javascript.

As you mentioned, the difference is minimal when there are few elements that you are creating, however, people get used to doing things wrong and I have come to see developments where they put a huge HTML code in a Jquery append because They are used to it and when they try to make animations they do not look fluid and they have some annoying flickers.

If you are going to occupy Jquery to create an element, do it in the best possible way by creating element by element and attribute by attribute

//Esto no es recomendable
$('#myDiv').append('<button id="myBtn">Jquery</button>');

//Mejor por partes
var btn = $("<button>").attr("id", "myBtn").text("Jquery");
$('#myDiv').append(btn);

It is better to do it that way since if you pass all the html to JQUERY you have to break the string into elements and attributes

    
answered by 06.11.2017 в 18:45