[TIP] Using PREPEND in Either jQuery or Pure JavaScript
Question
I was asked a question today about how to do the same thing as prepend in jQuery but without loading and using that library, so bascially to do it in pure JavaScript.For most programmers, this kind of “equivalency”, if you will, is often fairly easy to do and the reason we opt for libraries like jQuery is more for convenience and consistency than inability.
This is to show there is no magic to it (most of the time) and when you pull back the veil and understand what is happening, you realize that jQuery simply takes the pains of repetition and ugliness out of your code.
jQuery
... // api.jquery.com/prepend/ // jQuery API Documentation | .prepend( content [, content ] ) | Returns: jQuery // Syntax: $(selector).prepend(content,function(index,html)) // Description: Insert content, by parameter, to the beginning of each matched element. var x = $('destination-object'); var y = $('source-object'); x.prepend(y);
... // not too bad in jQuery $('destination-object').prepend($('source-object'));
JavaScript
... // www.w3schools.com/jsref/met_node_insertbefore.asp // W3Schools | .insertBefore(newItem, .childNodes[0]) // Returns: A Node Object of the inserted node // Syntax: node.insertBefore(newnode,existingnode) // Description: Inserts a node as child, right before an existing child, which you specify. var x = document.getElementById("destination-object"); var y = document.getElementById("source-object"); x.insertBefore(y, x.childNodes[0]);
... // this is INSANE document.getElementById("destination-object").insertBefore(document.getElementById("source-object"), document.getElementById("source-object").childNodes[0]);
For the love of all that is holly, don’t do these ugly one line chains please. Sacrifice a negligable amount of overhead and make your code more readable by expanding your syntax a bit to be more clear.
If for no other reason than to be self-serving and have an easier time debugging and detecting typos. Or, consider that you will type less in the long run which would actually make your code more efficient. If that wasn’t enough, consider that you will enjoy better logic flow and conceptualization as well.
Ultimately, to each their own, but hopefully this was a nice little token refresher. LLC away. — Mike
There should be no implication that jQuery is any less JavaScript, just that one is at its stock core and the other has extended functionality wrapped around it in a library that can expedite or shorthand a lot of what would be otherwise tediously long and ugly. That fact that a dedicated community of awesome people maintain the code all the time relieving you of having to constantly audit your code is just gravy.