ani_css ani_css - 2 months ago 21
Javascript Question

Class instead of getElementById

I want to use the Pikaday script and it gives me JavaScript code to add to my project. Something like:

var picker = new Pikaday({ field: document.getElementById('datepicker') });


Is there any way to use a class instead of
getElementByID
? For example:

var picker = new Pikaday({ field: $('.datepicker') });

Answer

if you are only using newer browsers you can use

document.querySelector('.datepicker')

This will give you the first element that matches the class. Here is the Caniuse link http://caniuse.com/#search=querySelector

For older browsers you can use

document.getElementsByClassName('datepicker')[0]