Here is my old code:
checkboxes = document.getElementsByName('foo');
As you know, checkboxes
will be an array. Now I need to limit selecting scope. So this is my new code:
checkboxes = $('.myclass input[name=foo]');
But in this case checkboxes
isn't an array anymore, it's a jQuery object. How can I make it the same as getElementsByName('foo')
's result?
Note that $('.myclass input[name=foo]')[0]
won't work either.
6 Answers 6
Try .toArray()
checkboxes = $('.myclass input[name=foo]').toArray();
Comments
Use this
var checked = [];
$.each($("input[name='foo']:checked"), function(){
checked.push($(this). val());
});
Comments
Charlie already pointed out that jQuery objects have a toArray()
function. That would work I think. Figured it was also worth noting that there is also a .makeArray()
function for generally converting array-like objects to native JavaScript arrays. https://api.jquery.com/jQuery.makeArray/
Comments
You can use .map()
and create an array of underlying DOM which getElementsByName()
returns
checkboxes = $('.myclass input[name=foo]').map(function(){ return this;}).get();
I would recommend @Charlie answer
You don't need to convert to Node elements array. Change your function to
function toggle(source, target) {
$(target).find('input[name=foo]').prop('checked', source.checked);
}
Usage
toggle(source, '.compare_people')
toggle(source, '.compare_posts')
2 Comments
document.querySelectorAll("input[name=foo]")
Comments
Getting javascript object from jquery object by $('selector')[0]
should work. See the answer from this link How to get javascript control from JQuery object?
I suspect your selector is the reason why the above approach doesn't work. Add double quotes to name value will make it work:
checkboxes = $('.myclass input[name="foo"]');
checkboxes
are inside an container whose class ismyclass
. Otherwise$('.myclass input[name=foo]')[0]
will definitely work..myclass
element and I don't want to select them. That's why I'm trying to use$('.myclass input[name=foo]')
instead ofdocument.getElementsByName('foo')
. Anyway, my question is a totally different thing..myclass
also an input?