<input id="a" type="radio" name="radioButton">
<input id="b" type="radio" name="radioButton">
<input id="c" type="radio" name="radioButton">
<input id="d" type="radio" name="radioButton">
Lets say I have four radio buttons and how do I make the first-child
to be checked
as default by using just javascript, no jQuery please.
This is what I have done but did not work. Thanks in advance.
document.querySelectorAll('[name=radioButon]:first-child').checked = true;
The reason your example wasn't working was because .querySelectorAll()
returns a NodeList
of elements. You would need to iterate over each element in the list in order to set the checked
property to true
:
var elements = document.querySelectorAll('[name=radioButton]:first-child');
Array.prototype.forEach.call(elements, function(el) { el.checked = true; });
Alternatively, you could also access the first matching element:
document.querySelectorAll('[name=radioButton]')[0].checked = true;
// or..
document.querySelector('[name=radioButton]').checked = true;
As a side note, you also had a typo.
The attribute selector [name=radioButon]
should have been [name=radioButton]
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments