I have a list of checkboxes which when checked I should get them and should retrieve their attribute values.
res.querySelectorAll('.node:checked')
Which gives me an array of checked input elements, I can use for loop to iterate through this array of elements and do
getAttribute('data-keyvalue')
on each. But is it possible to get them in one line only, something in
querySelectorAll
You can use Array#from
to convert output which is NodeList
of querySelectorAll
into array and then use array#map
to get the data-keyvalue
attribute of the checked checkbox.
var checkboxAttributes = Array.from(document
.querySelectorAll('.node:checked'))
.map(input => input.getAttribute('data-keyvalue'));
console.log(checkboxAttributes);
<input class="node" data-keyvalue="7" type="checkbox" checked>
<input class="node" data-keyvalue="8" type="checkbox">
<input class="node" data-keyvalue="9" type="checkbox" checked>
<input class="node" data-keyvalue="10" type="checkbox" checked>
<input class="node" data-keyvalue="11" type="checkbox">