Hayley Kiara Hayley Kiara - 6 months ago 11
Javascript Question

What's the equivalent of this code in pure/native javascript?

<label class="file">File</label>
<input class="none" type="file">


jQuery:

$('.file').click(function(){ $('.none').click();});

Answer

You can try this

 var _file = document.getElementsByClassName('file')[0]; //Return a NodeList
_file.onclick = function(){
  document.getElementsByClassName('none')[0].click();
}

jsFiddle

EDIT

If there are multiple elements with same class

var _file = document.getElementsByClassName('file'); //Return a NodeList
var _none =  document.getElementsByClassName('none');
for(var x = 0;x<_file.length;x++){
  (function(x){   //Creating closure 
   _file[x].addEventListener('click',function(){
   console.log(x)
     document.getElementsByClassName('none')[x].click();
   })
 }(x))
}

Demo2

Comments