Document Ready - DOMContentLoaded
document.addEventListener('DOMContentLoaded', function() { console.log("DOM Ready"); });
$(document).ready(function() {...});
window.addEvent('domready', function() {...});
document.observe("dom:loaded", function() {...});
Selecting an element - document.querySelector
var element = document.querySelector('#myElement'); var myStyledHeading = document.querySelector('h1.myCssClass');
Note that this returns just the first element that matches the selector even if there are more than 1 that match.
var element = $('#myElement');
var element = $$('#myElement');
var element = $('myElement');
You can use any sort of CSS selector as the parameter for querySelector - this makes it pretty flexible meaning you can use querySelector to select elements by ID, by class, by attribute, by ancestry or any valid combination.
var byId = document.querySelector('#id'); var byClass = document.querySelector('.className'); var byAttribute = document.querySelector('[attrKey=attrValue]'); var byAncestry = document.querySelector('#main div.content h1 p');
For attribute selectors as well as normal equals we can also use *= for contains the value anywhere (use ~= for values separated by whitespace), ^= for starts with, and $= for ends with. For example with <p example="hello world">
we could use [example*=world], [example^=hello], or [example$=world].
Selecting elements - document.querySelectorAll
var elements = document.querySelectorAll('a');
var elements = $('a');
var elements = $$('a');
var elements = $$('a');
Note that this returns a NodeList, not an array. If you want to use forEach
with the NodeList you can use the tried and tested call
approach:
[].forEach.call(elements, function(value, index, array) { console.log(value.innerHTML); });
Event Handling - addEventListener
var element = document.querySelector('#myElement'); element.addEventListener('click', function() { console.log("Element clicked"); });
click
can be replaced by the standard events - mouseover
, keydown
, blur
etc. Check out the W3.org specificaion for a complete list.
$('#myElement').bind('click', function() {...});
$$('#myElement').addEvent('click', function() {...});
$('myElement').observe('click',function() {...});
Change Styles - style
var element = document.querySelector('#myElement') element.style.color = '#ff0000'; element.style.fontFamily = 'sans-serif';
$('#myElement').css({'color':'#ff0000', fontFamily:'sans-serif'});
$$('#myElement').setStyles({'color':'#ff0000', fontFamily:'sans-serif'});
$('myElement').setStyle({'color':'#ff0000', fontFamily:'sans-serif'});
Change CSS Classes - classList
var element = document.querySelector('#myElement') element.classList.add('myClass'); element.classList.toggle('myClass'); // turns the style on if off, off if on. element.classList.remove('myClass');
$('#myElement').addClass('myClass');
$('#myElement').toggleClass('myClass');
$('#myElement').removeClass('myClass');
$$('#myElement').addClass('myClass');
$$('#myElement').toggleClass('myClass');
$$('#myElement').removeClass('myClass');
$('myElement').addClassName('myClass');
$('#myElement').toggleClassName('myClass');
$('#myElement').removeClassName('myClass');
Check element has class - classList.contains
var element = document.querySelector('#myElement') var hasClass = element.classList.contains('myClass'); // boolean
var hasClass = $('#myElement').hasClass('myClass');
var hasClass = $$('#myElement').hasClass('myClass');
var hasClass = $('myElement').hasClassName('myClass');
New Elements - createElement, appendChild & insertBefore
var newSource = document.createElement('script'); newSource.src = 'http://www.example.com/source.js'; document.body.appendChild(newSource); // Add an image before the new source element. var newImage = document.createElement('img'); newImage.src = 'http://www.example.com/image.png'; document.body.insertBefore(newImage, newSource);Note that for examples like there where there is a reference out to a URL (e.g.
script
's or img
's src
attribute) the browser will only load that resource once the element is added to the DOM. You could combine this with event listeners to do delayed/selective loading.
Attribute values - getAttribute & setAttribute
var element = document.querySelector('#myElement') element.setAttribute('name','elementName'); var attribute = element.getAttribute('name');
$('#myElement').attr('name', 'elementName');
var attribute = $('#myElement').attr('name');
$$('#myElement').set('name', 'elementName');
var attribute = $('#myElement').get('name');
$('myElement').writeAttribute('name', 'elementName');
var attribute = $('#myElement').readAttribute('name');
Iterating & Filtering arrays - Array.prototype.forEach & .filter
var array = ['a','b','c','d','e']; // Will return a new array with just ['a','e'] var voewelsOnly = array.filter(function(value, index, array) { return ("aeiou".indexOf(value) > -1); }); // Logs a e i o u in the console array.forEach(function(value, index, array) { console.log(value); });
Attribute checks - hasAttribute
var element = document.querySelector('#myElement') var hasAttr = element.hasAttribute('name'); // boolean
About
This site is about standard javascript for modern browsers that you can use to make your site great.We made the site because we were getting concerned about how there is a trend that seems to be developing for people treating javascript and jQuery as interchangeable (they aren't!) and making it increasingly difficult to just find that code snippet for that simple little bit of javascript that you want to code up; more often than not it seems that the first page of results on Google shows you how to do something with jQuery and not with plain, simple, vanilla standard javascript.
So we made this site partly to educate the world (ahem), but mainly for our own selfish reference when Google only wants to show us jQuery solutions.
"Why are you jQuery haters?"
We're not haters. We were like how probably many of you started out with basic javascript on our sites and, looking for a there-must-be-a-better-way, discovered jQuery. We loved it. We made great things. It worked in IE6. All was good in the world and we were happily coding away in javascript.But times changed - as our javascript skills developed and we really began to understand how to use javascript properly and modern, HTML5-compliant browsers with all the wonderful javascript support began to be the norm and not the exception. We took a look at what we were using in jQuery and realised that pretty much everything we needed to do could be done with standard javascript. No need for that 237kb (as of 2.0.2) of jQuery just to select a few elements on the page.
"But jQuery is about cross-browser support too!"
Correct - if you need to support old browsers then something like jQuery is a great choice. Some of the javascript we feature on this page simply wont work on old browsers. But modern browsers are getting pretty decent - IE6 is long dead now and we feel like its time to embrace the future and start using the features which by and large have 90+% support (based on caniuse.com's data analysis from September 2013), with the non-compatible users getting the "gracefully degredated" version.Privacy/EU Cookie Directive
This website does not use cookies, nor does it collect any personally identifiable information from you, but we do host various Google bits and pieces that do use cookies on our domain. These cookies are required to run advertising and visitor analytics software that allow us to run the site for free, and see how often people visit the site. You can opt out from these cookies at the Google sites below:- https://tools.google.com/dlpage/gaoptout
- http://www.google.com/ads/preferences/plugin/