getElementById and getElementByClassName

Neil_Bradley
Neil_Bradley used Ask the Experts™
on
The snippet here checks to see if the browser is mobile then adds type="date" to the 2 specified input fields.
    if(isMobile ) {
            document.getElementById('date1').type = 'date';
	        document.getElementById('date2').type = 'date';
        } else {

Open in new window

It works great.
Problem is I need to change the script to look for a class and not an id however I'm not having much look with he following
document.getElementsByClassName('date-pick').type = 'date';

Open in new window

Would really like to get this working so assistance approciated
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2013
Awarded 2012
Commented:
Hi,
question would be in plain JavaScript or in jQuery?

For plain JS it will be:
var targetElements = document.getElementsByClassName('date-pick');
for (var i = 0, aLen = targetElements.length; i < aLen; i++) {
  targetElements[i].type='date';
}

Open in new window


HTH
Rainer
Most Valuable Expert 2013
Awarded 2012
Commented:
So your complete sample would look like
if(isMobile ) {
	var targetElements = document.getElementsByClassName('date-pick');
	for (var i = 0, aLen = targetElements.length; i < aLen; i++) {
		targetElements[i].type='date';
	}
} else {

Open in new window

Neil_BradleyWeb UX/UI Developer

Author

Commented:
Thanks both. Worked perfectly..
Cheers,
Neil

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial