I have great respect for jQuery, but I also love the sheer power of vanilla JS.
Event Listeners (credits @alunny)
var $ = document.querySelectorAll.bind(document);
Element.prototype.on = Element.prototype.addEventListener;
$("somelink")[0].on('touchstart', handleTouch);
## DOM Manipulation
javascript
parent.appendChild(child) // append
parent.insertBefore(child, parent.childNodes[0]) // prepend
child.parentNode.removeChild(child) // remove
## Looping Through NodeList
javascript
[].forEach.call(document.querySelectorAll('a'), function(elem) {
console.log(elem.src);
});
## Convert NodeList to Array
javascript
myList = Array.prototype.slice.call(myNodeList);
## Select by Data Attribute
javascript
var matches = el.querySelectorAll('iframe[data-src]');
## Nesting Many Levels
javascript
var cells = document.querySelectorAll("#score>tbody>tr>td:nth-of-type(2)");
## Multiple IDs
javascript
var x = document.querySelector("#bar, #foo");
## Inline CSS
javascript
document.querySelector("#mainLink").style.cssText = 'color:red';
## Test if Element Contains
javascript
var child = document.querySelector('#child');
console.log(document.querySelector('parent').contains(child));
DYK?
getElementsByTagName()returns a Live NodeList which is faster thanquerySelectorAll()which returns a static NodeList.
#javascript#vanilla-js
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.