0

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.

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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"))

3 Comments

This looks good, but how can I make it so it only effects inputs in the options div?
Oh, I figured it out, change to... document.getElementById('options').getElementsByTagName("input")
Yep @CheeseFlavored that’s it, sorry I didn’t include that in my answer.
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.