As a simple experiment to get started, we’re going to use jQuery to append a new element to the body of a document. This should work in any context, provided you have a valid HTML5 file which has a <body> tag.
jQuery( 'body' ).append( '<div>Hello Worldling</div>' );
const el = document.createElement('div'); el.innerHTML( 'Hello Worldling' ); document.querySelector( 'body' ).appendChild( el );
As you can see from this very simple example the jQuery approach is more concise. However the plain JS approach doesn’t always lead to more code. The JS approach leads to more modularity because you build elements up line by line, for instance to add an ID to your newly created element looks like this:
const el = document.createElement('div'); el.id = 'product-283';
Similarly we can add CSS classes to elements using el.className:
const el = document.createElement('div'); el.className = 'product-item';
With jQuery we could use the same approach where we build elements in a more modular approach, but we also have the option to inject elements into the DOM in a more monolithic approach using append() or html() where we insert the entire block of code as shown below:
jQuery( '#product-item-row' ).append( '<button id="product-pay-now-1928" class="pay-now-button">Pay Now</button>' );
This doesn’t mean we can’t build up elements with jQuery, we can make the element and add attributes to it before appending.
let targetEl = jQuery( '#product-item-row' ); var button = jQuery( '<button></button>' ); button.html( 'Pay Now' ); button.attr( 'id', 'product-pay-now-1928' ); button.addClass( 'pay-now-button' ); targetEl.append( button );