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">
Check the console
, it will log an array of checked data attributes values.
var chk = Array.prototype.slice.call(document.querySelectorAll('.node:checked')).map(function(node) { return node.getAttribute('data-keyvalue'); }) console.log(chk);
<input type="checkbox" class="node" checked data-keyvalue="1" /> <input type="checkbox" class="node" checked data-keyvalue="2" /> <input type="checkbox" class="node" checked data-keyvalue="3" /> <input type="checkbox" class="node" data-keyvalue="4" /> <input type="checkbox" class="node" data-keyvalue="5" /> <input type="checkbox" class="node" checked data-keyvalue="6" /> <input type="checkbox" class="node" checked data-keyvalue="7" />
I came across the same issue, in the end all my searching amounted to, you have to process them one at a time and build either an array or string yourself. Try creating a function that does this for you and whenever you need to get them all, the function will give you data in the format you need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.