How jQuery Selectors Work With document.append() – jQuery To Vanilla JS

A week ago I attended FITC’s Web Unleashed, a conference for front-end developers. There I participated in a talk by Luke DeWitt titled “A Very Public and Overdue Funeral for jQuery.” Luke described all the ways that web development has grown out of jQuery. Standards are so much better now then they were in 2006. For example:

We don’t need the jQuery selector because we have querySelector().

We don’t need $.class() anymore because we have classList()

We don’t need $.data() anymore because we have dataset()

These are all standard now in all browsers as of IE 11. With easy polyfills for earlier support. So if you’re not targeting legacy browsers, why do need jQuery?

One of my clients has a site that uses jQuery and I ran across this gotcha when moving some features to vanilla JS. There is a function that sends in a jQuery object thats has the text for a modal in HTML. I had to take the current embed and add another template to display beside it.

See the Pen document.append() – jQuery To Vanilla JS example 1 by Brian Best (@brianbest) on CodePen.5308

This is similar to how the code was working prior to the new feature. $(‘#foo’).html() works because we are directly pasting in the html string into a innerHTML. Watch what happens when we try combining two templates using the append() function.

See the Pen document.append() – jQuery To Vanilla JS example 2 by Brian Best (@brianbest) on CodePen.5308

The issue now is the browser sees the HTML output as a literal string. append() expects to get a DOM node as an input, but here $(‘#template’).html() is only sending in the string of what is in its innerHTML. As we can see with $(‘#template-list’), the jQuery selector does not return a DOM node but a jQuery object.

See the Pen document.append() – jQuery To Vanilla JS example 3 by Brian Best (@brianbest) on CodePen.5308

To get both #template and #template-list to appear using append() we need to find the DOM node in the jQuery object. Luckily the fix is quite simple as using $(‘#template’)[0] returns the DOM node from within the jQuery object.

 

Leave a reply:

Your email address will not be published.

Site Footer