Native equivalents of jQuery functions
If you are just targetting modern browsers and want more performance, it maybe a good idea to use native functions instead. Lee Brimelow wrote a very nice article on it. Some notes/summary below:
Selecting elements
// Selecting a tag
document.getElementsByTagName("div")
// Selecting all elements with a CSS class
document.getElementsByClassName("my-class")
// Get by generic CSS selector (very similar to `$("..."))
document.querySelectorAll("#elemId div:first-child")
// Just get the first element found
document.querySelector("#elemId div:first-child")
DOM manipulation
// Append HTML element
var frag = document.createDocumentFragment();
var div = document.createElement("div");
div.id = "someId";
var img = document.createElement("img");
img.src = "img.png";
div.appendChild(img);
frag.appendChild(div);
// append
document.body.appendChild(frag);
// prepend
document.body.insertBefore(frag,
document.body.firstChild);
CSS classes
var el = document.querySelector("...")
// adding class
el.addClass("className")
// remove class
el.classList.remove("className")
// has a class?
el.classList.contains("className")
Modify CSS
el.style.background = "#FFF"
el.style.color = "#222"
But wonder if the performance difference between jQuery 2 (targets mainly modern browsers) will perform compared to native equivalents, perhaps they will be more negligible
Written by Jiew Meng
Related protips
3 Responses
This is a nice post but I'm afraid that many of us will still need to go through the pain of supporting older browsers (although, hopefully not much longer!) which would, subsequently, realistically require the use of jQuery.
But you have a good point in regards to jQuery 2.
@davidandrewsmit I guess for most "work" related projects, esp those for larger companies, supporting old browsers will still be required. But like u said hopefully not for long.
@jiewmeng that's the most beautiful thing about jQuery 2; it has dropped support for IE 7 and 8 so future clients will be told that certain aspects of their websites will be held back if IE 7/8 needs to be supported, which, hopefully, will push clients to say "okay, let's focus on IE9+" which would push users of these older browsers to upgrade once and for all!