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

jQuery:

$('.file').click(function(){ $('.none').click();});
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • You even no need any js for that equivalent. Your best bet would be just to wrap your input inside label https://jsfiddle.net/ehp5v1rm/ That's how it should be done – A. Wolff May 30 '16 at 09:28

2 Answers2

6

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

brk
  • 48,835
  • 10
  • 56
  • 78
  • 1
    What if there are multiple elements having class `file` & `none`. – Tushar May 30 '16 at 08:58
  • OP has not mentioned about multiple class. If it is so then have to loop and add addEventListener – brk May 30 '16 at 08:59
  • `$('.none').click();` is the same as `.trigger('click')`, which triggers event on **all** elements. [demo fiddle](https://jsfiddle.net/br3b3ty4/), so You should call `.click()` on all `document.getElementsByClassName('none')` (nested loop) – Bogdan Kuštan May 30 '16 at 09:15
  • `getElementsByClassName` returns a `HTMLCollection`, not a `NodeList` (there's a big difference when accessing it, also in performance) – Aloso May 30 '16 at 09:18
0

This might be the most accurate equivalent:

document.querySelector(".file")
    .addEventListener("click", function(){
  document.querySelector(".none").click();
});

For a more cross-browser alternative for .click(): How can I trigger a JavaScript event click

Community
  • 1
  • 1
Aloso
  • 5,123
  • 4
  • 24
  • 41