jQuery: Select an element by name


Although the title says jQuery in it, I will also provide Javascript solution for this snippet.

Live Demo at CodePen

Suppose we have the following checkbox input:
<input type="checkbox" name="colors" value="red" /> Red
<input type="checkbox" name="colors" value="green" /> Green
<input type="checkbox" name="colors" value="blue" /> Blue

in jQuery:
var colors = $('[name="colors"]'); // non-element specific
var colors = $('input[name="colors"]'); // specific to "input" elements only

in JavaScript:
// returns array of elements with name="colors"
var colors = document.getElementsByName('colors');
var colors = document.querySelectorAll('[name="colors"]');

// returns first element with name="colors"
var colors = document.getElementsByName('colors')[0];
var colors = document.querySelector('[name="colors"]');



Comments