Is there any elegant way of turning [$(div), $(span), $(li)] into $(div, span, li)?
What I need is a jQuery-wrapped set of elements instead of
I have a similar problem long time ago. I have a huge form and I need to get every input. So, my idea was take each input as jQuery object and turn it into jQuery wrapped set of elements. How can I do that? Well this is the solution for your question.
let fields = $([]);. 'form#details :input' as jQuery Objects. .each method to extract the information that you need, and add the jQuery object to the jQuery set wrapper: fields = fields.add(input);If you have a list of elements let elements = [$('#gw_id'), $('#erv_id'), $('#name')]; you can replace $('form#details :input') with elements;
Another, alternative is to use .reduce vanilla js. in this let set = $(elements.reduce((acc, cur) => {return acc.concat(cur.get())}, [])); snippet we use the array of elements and apply reduce reduce has 4 parameters but we can use the first two that are accumulator as acc and currentValue as cur also we use the Arrow function (=>) to reduce the callback. In this callback we concatenate each current value in a new array. Finally, the return array is wrapped into a jQuery object $(). You can replace elements with $('form#details :input') also.
let fields = $([]);
let elements = [$('#gw_id'), $('#erv_id'), $('#name')];
$(function() {
console.log('List of fields: ');
$('form#details :input').each((index, value) => {
let input = $(value);
let id = input.attr('id');
let type = input.attr('type');
fields = fields.add(input);
if (id && type == 'text') {
console.log('Input: ' + id + ' | Text: ' + type);
}
});
fields.addClass('ui-state-error');
let set = $(elements.reduce((acc, cur) => {
return acc.concat(cur.get())
}, []));
console.log('Set list: ');
set.each((index, value) => {
let input = $(value);
let id = input.attr('id');
let type = input.attr('type');
console.log('Input: ' + id + ' | Text: ' + type);
});
});
.ui-state-error {
background: yellow;
}