File selector

The selector :file selects elements of type file, which are file upload fields. The equivalent of $(':file') is $('[type=file]'). Since :file is not part of the CSS specification, for better performance in modern browsers it is better to use [type='file'] instead.

Syntax

This is how we select elements with type file:

javascript$(':file');

As with other pseudo-class selectors (those starting with ':'), it is better to precede ':' with the name of a tag or another selector, otherwise the selector '*' will be applied, i.e. $(':file') will be treated as $('*:file'), so it is better to use $('input:file') instead.

Example

Let's select all inputs with the type file and give them a green background and a red border using the css method:

html<form>
  <input type="button" value="button">
  <input type="file">
  <input type="password">
  <button>button</button>
  <input type="reset">
  <input type="radio" name="test">
  <input type="radio" name="test">
  <input type="checkbox">
  <input type="text">
</form>

<

+javascript+> $('form input:file').css({background: 'green', border: '2px red solid'}); $('form').submit(function(event) { event.preventDefault(); // prevents form submission });

<

-javascript->

See also

  • method filter,
    which filters elements in a set by a given selector
  • method find,
    which searches for elements within those already found
  • method css,
    which allows you to get and change the CSS styles of an element