I am selecting all input elements with class "img-title" in order to get an array with the current value of these inputs:
var values = []
for (let element of $(".img-title")){
values.push( element.val() ) }
But this doesn't work, because the elements of $(".img-title") are not the references to the inputs as I expected, but the html code, so val() rises an error. Is there a simple way to get the array with the current values of the inputs with class "img-title" ?
1 Answer 1
When you use for..of over a jQuery collection, the items you get back are the elements themselves, not a jQuery collection which contains that element. Either turn the element into a jQuery collection first before calling .val() on it:
const values = []
for (const element of $(".img-title")){
values.push( $(element).val() )
}
Or, access the property on the native element just with .value:
const values = []
for (const element of $(".img-title")){
values.push( element.value )
}
Or, consider using .map instead:
const values = $(".img-title")
.map(function() {
return $(this).val();
})
.get();
(make sure to use .get() at the end, to get the array, rather than the jQuery collection)
Or, avoid jQuery entirely if you want, no need to include a big library for something as simple as this:
const values = Array.prototype.map.call(
document.querySelectorAll('.img-title'),
element => element.value
);