Reputation: 2112
I have several checkboxes on my page in a div called OPTIONS. like this
<div id="options">
<input type="checkbox"..... >
<input type="checkbox"..... >
<input type="checkbox"..... >
<input type="checkbox"..... >
<input type="checkbox"..... >
...
...
</div>
Since I know every input in this div will always be a checkbox, I was wondering if there's a way in css or javascript to make them automatically be checkboxes without me typing type="checkbox"
each time.
Upvotes: 0
Views: 49
Reputation: 44097
Yes, you can just do this in JavaScript like so:
var inputs = Array.from(document.getElementsByTagName("input"));
inputs.forEach(function(elem) {
elem.setAttribute("type", "checkbox");
})
This converts the NodeList of <input>
elements into an array which then sets the type
attribute.
Here’s a jQuery/ES6 way of doing it too:
$("input").each(elem => elem.attr("type", "checkbox"))
Upvotes: 1
Reputation: 4768
document.addEventListener('DOMContentLoaded', function() {
let inputs = document.querySelectorAll('#options input');
for(let input of inputs) {
console.log(input);
input.type = 'checkbox';
}
});
<div id="options">
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input>
<input><input>
<input>
<input>
<input>
<input><input>
<input>
<input>
<input>
<input><input>
<input>
<input>
<input>
<input>
</div>
Upvotes: 1
Reputation: 50291
Setting in the html will be better option. By default input type is text
and changing the type through javascript will be a slower process then setting it directly in html
If you still opt to do that you can target the element , get it's children and then loop over it and change the type using setAttribute
document.getElementById('options').children
will give a collection, using spread operator ...
so that array method can be used
[...document.getElementById('options').children].forEach(item => {
item.setAttribute('type', 'checkbox')
})
<div id="options">
<input>
<input>
<input>
<input>
<input>
</div>
Upvotes: 2